package com.css.fxfzypg.modules.model.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.SettingSeismic.entity.SeismicIntensityRelation;
import com.css.fxfzypg.modules.SettingSeismic.entity.SettingSeismicDetails;
import com.css.fxfzypg.modules.SettingSeismic.service.IntensityRelationService;
import com.css.fxfzypg.modules.SettingSeismic.service.SettingSeismicService;
import com.css.fxfzypg.modules.baseData.entity.BuildingVulnerability;
import com.css.fxfzypg.modules.baseData.entity.PbeEntity;
import com.css.fxfzypg.modules.baseData.service.BuildingVulnerabilityService;
import com.css.fxfzypg.modules.model.entity.DataPbeInjuriesVo;
import com.css.fxfzypg.modules.model.entity.DataPbeIntStrArea;
import com.css.fxfzypg.modules.preAssessResult.entity.SeiCapDistribution;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.resultupload.service.ResultTotalService;
import com.css.fxfzypg.modules.similitudeAnalyse.utils.BeanUtil;
import com.css.fxfzypg.modules.model.entity.Casualty;
import com.css.fxfzypg.modules.model.entity.DataPbeInjuries;
import com.css.fxfzypg.modules.model.repository.CasualtyRepository;
import com.css.fxfzypg.modules.model.service.CasualtyService;
import com.css.fxfzypg.modules.model.to.CasualtyTO;
import com.css.fxfzypg.modules.model.vo.CasualtyVO;
import com.css.fxfzypg.modules.preAssessResult.entity.Vulnerability;
import com.css.fxfzypg.modules.preAssessResult.entity.VulnerabilityVO;
import com.css.fxfzypg.modules.preAssessResult.service.PreAssessResultService;
import com.css.fxfzypg.modules.preAssessResult.vo.StructuralProportionVo;
import com.css.fxfzypg.modules.resultupload.repository.ResultTotalRepository;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultDetailsEntity;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultMainEntity;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.geotools.data.FeatureWriter;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.MultiPolygon;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Dbj
 * @date 2022年09月27日  17:17
 */
@Service
public class CasualtyServiceImpl implements CasualtyService {

    @Resource
    private SysRoleService roleService;
    @Resource
    private CasualtyRepository casualtyRepository;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    SUserService sUserService;
    @Resource
    private SysAreaService areaService;
    @Resource
    BuildingVulnerabilityService buildingVulnerabilityService;
    @Resource
    PreAssessResultService preAssessResultService;
    @Resource
    ResultTotalRepository resultTotalRepository;
    @Resource
    IntensityRelationService intensityRelationService;
    @Resource
    SettingSeismicService settingSeismicService;
    public static final int BATCH_SIZE = 1000;
    @Resource
    ResultTotalService resultTotalService;
    @Resource
    PreAssessTaskService preAssessTaskService;
    @Value("${image.localDir}")
    private String localDir;

    @Override
    public Map<String, Object> getPage(CasualtyTO casualtyTO, int curPage, int pageSize) {
        Map<String, String> areaMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaMap"));
        Map<String, String> orgMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgMap"));
        String userId = PlatformSessionContext.getUserID();
        casualtyTO.setUserId(userId);
        //根据用户id查询角色信息 用于数据的查询范围
        String roleByUserId = roleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(roleByUserId, Map.class);
        for (Map roleMap : roleMaps) {
            String roleCode = (String) roleMap.get("roleCode");
            if (roleCode.equals(FxfzConstants.YPG_COUN_YW_ROLE) || roleCode.equals(FxfzConstants.YPG_COUN_GL_ROLE)) {
                casualtyTO.setNation(true);
            }
        }
        if (casualtyTO.getNation() == null) {
            casualtyTO.setNation(false);
        }
        Map<String, Object> page = casualtyRepository.findPage(casualtyTO, curPage, pageSize);
        List<Casualty> casualtyList = (List<Casualty>) page.get("rows");
        List<CasualtyVO> vos = new ArrayList<>(casualtyList.size());
        for (Casualty casualty : casualtyList) {
            CasualtyVO vo = new CasualtyVO();
            BeanUtil.copy(casualty, vo);
            vo.setProvince(areaMap.get(casualty.getProvince()));
            if (!"全部".equals(casualty.getCity())) {
                StringBuffer buffer = new StringBuffer();
                List<String> cityList = Arrays.asList(casualty.getCity().split(","));
                for (String s : cityList) {
                    buffer.append(areaMap.get(s)).append(",");
                }
                String cityName = buffer.toString();
                vo.setCity(cityName.substring(0, cityName.length() - 1));
            }
            vo.setProvince(areaMap.get(casualty.getProvince()));
            vos.add(vo);
            //casualty.setIsDefault("1".equals(casualty.getIsDefault())?"是":"否");
        }
        page.put("rows", vos);
        return page;
    }

    @Override
    public Map<String, Object> getPageForXczh(CasualtyTO casualtyTO, int curPage, int pageSize) {
        Map<String, String> areaMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaMap"));
        Map<String, Object> page = casualtyRepository.findPageForXczh(casualtyTO, curPage, pageSize);
        List<Casualty> casualtyList = (List<Casualty>) page.get("rows");
        List<CasualtyVO> vos = new ArrayList<>(casualtyList.size());
        for (Casualty casualty : casualtyList) {
            CasualtyVO vo = new CasualtyVO();
            BeanUtil.copy(casualty, vo);
            if (!"全部".equals(casualty.getCity())) {
                StringBuffer buffer = new StringBuffer();
                List<String> cityList = Arrays.asList(casualty.getCity().split(","));
                for (String s : cityList) {
                    buffer.append(areaMap.get(s)).append(",");
                }
                String cityName = buffer.toString();
                vo.setCity(cityName.substring(0, cityName.length() - 1));
            }
            vo.setProvince(areaMap.get(casualty.getProvince()));
            vos.add(vo);
            //casualty.setIsDefault("1".equals(casualty.getIsDefault())?"是":"否");
        }
        page.put("rows", vos);
        return page;
    }

    @Override
    public Casualty getModelById(String id) {
        Map<String, String> areaMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaMap"));
        Map<String, String> orgMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgMap"));
        Casualty casualty = casualtyRepository.getModelById(id);
        casualty.setProvince(areaMap.get(casualty.getProvince()));
        if (!"全部".equals(casualty.getCity())) {
            StringBuffer buffer = new StringBuffer();
            List<String> cityList = Arrays.asList(casualty.getCity().split(","));
            for (String s : cityList) {
                buffer.append(areaMap.get(s)).append(",");
            }
            String cityName = buffer.toString();
            casualty.setCity(cityName.substring(0, cityName.length() - 1));
        }
//        CasualtyVO vo = new CasualtyVO();
//        BeanUtil.copy(casualty,vo);
        return casualty;
    }

    @Override
    public Casualty getDefaultModel() {
        return casualtyRepository.getDefaultModel();
    }

    @Override
    public List<Casualty> getByDivision(String province, String city, int isNa) {
        return casualtyRepository.getByDivision(province, city, isNa);
    }

    @Override
    public CasualtyVO getModelByIdForCopy(String id) {
        Map<String, String> orgMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgMap"));
        Casualty casualty = casualtyRepository.getModelById(id);
        CasualtyVO vo = new CasualtyVO();
        BeanUtil.copy(casualty, vo);
        vo.setModelName("");
        vo.setIsDefault("0");
        vo.setCity("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        vo.setCreateUserId(userId);
        vo.setCreateUserName(sUser.getUserName());
        vo.setOrgId(sUser.getOrgId());
        vo.setOrgName(orgMap.get(sUser.getOrgId()));
        vo.setIsValid(YNEnum.Y.toString());
        return vo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Casualty casualty) {
        Map<String, String> orgMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgMap"));
        String userId = PlatformSessionContext.getUserID();
        casualty.setId(UUIDGenerator.getUUID());
        casualty.setCreateUserId(userId);
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        casualty.setCreateUserName(sUser.getUserName());
        casualty.setCreateTime(new Date());
        casualty.setOrgId(sUser.getOrgId());
        String orgName = orgMap.get(sUser.getOrgId());
        casualty.setOrgName(orgName);
        casualty.setIsValid(YNEnum.Y.toString());
        //获取省code
        String areaCode = areaService.getDivisionCodeById(casualty.getProvince());
        areaCode = (String) JSONObject.parse(areaCode);
        casualty.setProvinceCode(areaCode);
        casualtyRepository.save(casualty);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Casualty casualty) {
        Casualty modelById = casualtyRepository.getModelById(casualty.getId());
        String userId = PlatformSessionContext.getUserID();
        if (!userId.equals(casualty.getCreateUserId())) {
            throw new RuntimeException("修改失败，只能修改自己创建的模型");
        }
        BeanUtil.copy(casualty, modelById);
        casualty.setUpdateUserId(userId);
        casualty.setUpdateTime(new Date());
        casualtyRepository.update(casualty);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        Casualty casualty = casualtyRepository.getModelById(id);
        String userId = PlatformSessionContext.getUserID();
        if (!userId.equals(casualty.getCreateUserId())) {
            throw new RuntimeException("删除失败，只能删除自己创建的模型");
        }
        casualtyRepository.delete(userId, new Date(), id);
    }

    @Override
    public Casualty getDefaultModel(String taskId) {
        Casualty casualty = casualtyRepository.getDefaultModel(taskId);
        //处理数据
        return resetSasualty(casualty);
    }

    private Casualty resetSasualty(Casualty casualty) {
        Map<String, String> areaMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaMap"));
        Map<String, String> orgMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "orgMap"));
        casualty.setProvince(areaMap.get(casualty.getProvince()));
        if (!"全部".equals(casualty.getCity())) {
            StringBuffer buffer = new StringBuffer();
            List<String> cityList = Arrays.asList(casualty.getCity().split(","));
            for (String s : cityList) {
                buffer.append(areaMap.get(s)).append(",");
            }
            String cityName = buffer.toString();
            casualty.setCity(cityName.substring(0, cityName.length() - 1));
        }
        return casualty;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void calculate(String modeId,String taskId) throws Exception{
//        basicDataService.deleteSettingSeismicPbeByTaskId(taskId);
//        Long start = System.currentTimeMillis();
//        Casualty model = casualtyRepository.getModelById(modeId);
//        @NotNull(message = "计算死亡人数系数不能为空") BigDecimal deathNumber = model.getDeathNumber();
//        @NotNull(message = "受伤人数系数不能为空") BigDecimal injuries = model.getInjuries();
//        if(PlatformObjectUtils.isEmpty(model)){
//            throw  new RuntimeException("请选择人员伤亡模型");
//        }
//        List<CenterResult> centerList = new ArrayList<>();
//        List<Vulnerability> allVulnerability = basicDataService.getAllVulnerabilityByTaskId(taskId);
//        Map<String, Vulnerability> structureAndIntensityMap = new HashMap<>();
//        if (PlatformObjectUtils.isNotEmpty(allVulnerability)) {
//            //<建筑物类别,<损坏,0.25>>
//            structureAndIntensityMap = getStructureAndIntensity(allVulnerability);
//        }
//        //basicDataService.deleteCenterResultByTaskId(taskId);
//        List<SettingSeismicDetails> settingSeismicDetails = settingSeismicService.getSettingSeismicDetailsByTaskId(taskId);
//        if(PlatformObjectUtils.isNotEmpty(settingSeismicDetails)){
//            //总的死亡人数
//            BigDecimal maxDeathPerson = new BigDecimal(0) ;
//            BigDecimal minDeathPerson = new BigDecimal(0);
//            //最大最小受伤人数
//            BigDecimal maxInjuredPerson = new BigDecimal(0);
//            BigDecimal minInjuredPerson = new BigDecimal(0);
//            BigDecimal earthLevel = settingSeismicDetails.get(0).getEarthquakeLevel();
//            String id = settingSeismicDetails.get(0).getId();
//            //死亡人数
//            BigDecimal deathTotalNum = new BigDecimal(0);
//            //受伤人数
//            BigDecimal injuredTotalNum = new BigDecimal(0);
//            SettingSeismicDetails detail = null;
//            for(int dd=0;dd<settingSeismicDetails.size();dd++){
//                detail = settingSeismicDetails.get(dd);
//                if(deathTotalNum.compareTo(maxDeathPerson)>0){
//                    maxDeathPerson = deathTotalNum;
//                }
//                if(deathTotalNum.compareTo(minDeathPerson)<0){
//                    minDeathPerson = deathTotalNum;
//                }
//                if(injuredTotalNum.compareTo(maxInjuredPerson)>0){
//                    maxInjuredPerson = injuredTotalNum;
//                }
//                if(injuredTotalNum.compareTo(minInjuredPerson)<0){
//                    minInjuredPerson = injuredTotalNum;
//                }
//                deathTotalNum = new BigDecimal(0);
//                injuredTotalNum = new BigDecimal(0);
//                List<SettingSeismicInfluenceflied> influenceList = settingSeismicInfluencefliedRepository.findSettingSeismicInfluencefliedById(settingSeismicDetails.get(dd).getId());
//                if(PlatformObjectUtils.isNotEmpty(influenceList)){
//                    for (int bb=0;bb<influenceList.size();bb++) {
//                        List<PbeEntity> pbeList = pbeService.getPbeByInfluenceflieId(influenceList.get(bb).getUuid());
//                        if(PlatformObjectUtils.isNotEmpty(pbeList)){
//                            for (PbeEntity pbeEntity : pbeList) {
//                                //地震id
//                                String earthquakeId = influenceList.get(bb).getSourceEarthquakeId();
//                                //影响场id
//                                String influenceflieId = influenceList.get(bb).getUuid();
//                                //格网id
//                                String pbeId = pbeEntity.getPbeId();
//                                //获取格网下的面积
//                                BigDecimal area = new BigDecimal(pbeEntity.getCoveredarea());
//                                if(area.compareTo(new BigDecimal(0))==0){
//                                    continue;
//                                }
//                                BigDecimal hRatio = new BigDecimal(0);
//                                BigDecimal steelRatio = new BigDecimal(0);
//                                BigDecimal cRatio = new BigDecimal(0);
//                                BigDecimal bRatio = new BigDecimal(0);
//                                BigDecimal bmRatio = new BigDecimal(0);
//                                BigDecimal sRatio = new BigDecimal(0);
//                                BigDecimal wRatio = new BigDecimal(0);
//                                BigDecimal stRatio = new BigDecimal(0);
//                                BigDecimal oRatio = new BigDecimal(0);
//
//                                StructuralProportionVo structuralProportion = preAssessResultService.getStructuralProportion(pbeEntity);
//                                if(PlatformObjectUtils.isNotEmpty(structuralProportion)){
//                                    if("城镇".equals(pbeEntity.getTownorcontry())){
//                                        hRatio = structuralProportion.getDhpTownHighTatio();
//                                        steelRatio = structuralProportion.getDhpTownSteelTatio();
//                                        cRatio = structuralProportion.getDhpTownBetonTatio();
//                                        bRatio = structuralProportion.getDhpTownBrickTatio();
//                                        bmRatio = structuralProportion.getDhpTownMasonryTatio();
//                                        sRatio = structuralProportion.getDhpTownSoilTatio();
//                                        wRatio = structuralProportion.getDhpTownWoodTatio();
//                                        stRatio = structuralProportion.getDhpTownStoneTatio();
//                                        oRatio = structuralProportion.getDhpTownOtherTatio();
//                                    }else if("农村".equals(pbeEntity.getTownorcontry())){
//                                        hRatio = structuralProportion.getDhpVillageHighTatio();
//                                        steelRatio = structuralProportion.getDhpVillageSteelTatio();
//                                        cRatio = structuralProportion.getDhpVillageBetonTatio();
//                                        bRatio = structuralProportion.getDhpVillageBrickTatio();
//                                        bmRatio = structuralProportion.getDhpVillageMasonryTatio();
//                                        sRatio = structuralProportion.getDhpVillageSoilTatio();
//                                        wRatio = structuralProportion.getDhpVillageWoodTatio();
//                                        stRatio = structuralProportion.getDhpVillageStoneTatio();
//                                        oRatio = structuralProportion.getDhpVillageOtherTatio();
//                                    }
//                                }else{
//                                    throw new RuntimeException("获取不到对应的建筑物比例");
//                                }
//
//                                //拿到格网下的每类建筑物的占比窃取每类建筑物的面积
//                                //假设面积比例
//                                //高层建筑 0.1
//                                BigDecimal hArea = area.multiply(hRatio);
//                                //钢结构 0.1
//                                BigDecimal steelArea = area.multiply(steelRatio);
//                                //多层钢筋混凝土结构 0.2
//                                BigDecimal cArea = area.multiply(cRatio);;
//                                //砖混结构 0.15
//                                BigDecimal bArea = area.multiply(bRatio);;
//                                //砖木结构 0.15
//                                BigDecimal bmArea = area.multiply(bmRatio);;
//                                //土结构 0.15
//                                BigDecimal sArea = area.multiply(sRatio);;
//                                //木结构 0.1
//                                BigDecimal wArea = area.multiply(wRatio);;
//                                //石结构 0.1
//                                BigDecimal stArea = area.multiply(stRatio);;
//                                //其他结构 0.05
//                                BigDecimal oArea = area.multiply(oRatio);;
//                                //拿到建筑物易损性信息求取该格网下每类建筑物的易损面积
//                                //总的损坏面积=各类建筑类别的损坏面积之和
//                                BigDecimal totalDdArea = new BigDecimal(0);
//                                if(structureAndIntensityMap.size()>0){
//                                    Iterator<Map.Entry<String, Vulnerability>> iterator = structureAndIntensityMap.entrySet().iterator();
//                                    while(iterator.hasNext()){
//                                        BigDecimal temp = new BigDecimal(0);
//                                        Map.Entry<String, Vulnerability> next = iterator.next();
//                                        String structureType = next.getKey();
//                                        Vulnerability vulnerability = next.getValue();
//                                        BigDecimal basic = null;
//                                        BigDecimal slight = null;
//                                        BigDecimal mid = null;
//                                        BigDecimal serious = null;
//                                        BigDecimal damage = null;
//                                        if(PlatformObjectUtils.isNotEmpty(vulnerability)){
//                                            basic = vulnerability.getBasicallyIntact();
//                                            slight = vulnerability.getMinorDamage();
//                                            mid = vulnerability.getModerateDamage();
//                                            serious = vulnerability.getSeriousDamage();
//                                            damage = vulnerability.getDamage();
//                                            if(FxfzConstants.HIGH_STRUCTURE.equals(structureType)){
//                                                temp = hArea;
//                                            }else if(FxfzConstants.STEEL_STRUCTURE.equals(structureType)){
//                                                temp = steelArea;
//                                            }else if(FxfzConstants.HNT_STRUCTURE.equals(structureType)){
//                                                temp = cArea;
//                                            }else if(FxfzConstants.ZH_STRUCTURE.equals(structureType)){
//                                                temp = bArea;
//                                            }else if(FxfzConstants.ZM_STRUCTURE.equals(structureType)){
//                                                temp = bmArea;
//                                            }else if(FxfzConstants.SOIL_STRUCTURE.equals(structureType)){
//                                                temp = sArea;
//                                            }else if(FxfzConstants.WOOD_STRUCTURE.equals(structureType)){
//                                                temp = wArea;
//                                            }else if(FxfzConstants.STONE_STRUCTURE.equals(structureType)){
//                                                temp = stArea;
//                                            }else if(FxfzConstants.OTHER_STRUCTURE.equals(structureType)){
//                                                temp = oArea;
//                                            }
//                                            //获取不同破损程度下的不同建筑物类别的面积
//                                            //基本完好
//                                            BigDecimal bdArea = basic.compareTo(new BigDecimal(0.00))==0?basic:basic.multiply(temp);
//                                            //轻微破坏
//                                            BigDecimal sdArea = slight.compareTo(new BigDecimal(0.00))==0?slight:slight.multiply(temp);
//                                            //中等破坏
//                                            BigDecimal mdArea = mid.compareTo(new BigDecimal(0.00))==0?mid:mid.multiply(temp);
//                                            //严重破坏
//                                            BigDecimal sedArea = serious.compareTo(new BigDecimal(0.00))==0?serious:serious.multiply(temp);
//                                            //损坏
//                                            BigDecimal ddArea = damage.compareTo(new BigDecimal(0.00))==0?damage:damage.multiply(temp);
//                                            totalDdArea = totalDdArea.add(ddArea);
//                                            //保存计算中间结果
//                                            CenterResult centerResult = new CenterResult();
//                                            centerResult.setTaskId(taskId);
//                                            centerResult.setEarthquakeId(earthquakeId);
//                                            centerResult.setInfluenceflieId(influenceflieId);
//                                            centerResult.setPbeId(pbeId);
//                                            centerResult.setStructureType(structureType);
//                                            centerResult.setBasicArea(bdArea);
//                                            centerResult.setBasic(basic);
//                                            centerResult.setSlightArea(sdArea);
//                                            centerResult.setSlight(slight);
//                                            centerResult.setMidArea(mdArea);
//                                            centerResult.setMid(mid);
//                                            centerResult.setSeriousArea(sedArea);
//                                            centerResult.setSerious(serious);
//                                            centerResult.setDamageArea(ddArea);
//                                            centerResult.setDamage(damage);
//                                            centerResult.setArea(area);
//                                            centerResult.setPopulation(new BigDecimal(pbeEntity.getPopulation()));
//                                            centerList.add(centerResult);
//                                            // basicDataService.save(centerResult);
//                                        }
//                                    }
//                                }
//                                //计算死亡比
//                                BigDecimal deathPercent = totalDdArea.divide(area,2,BigDecimal.ROUND_HALF_UP);
//                                //计算死亡人数
//                                BigDecimal deathPersonCount = deathNumber.multiply(new BigDecimal(pbeEntity.getPopulation())).multiply(deathPercent);
//                                deathTotalNum = deathTotalNum.add(deathPersonCount);
//                                BigDecimal injuryPerson = deathPersonCount.multiply(injuries);
//                                injuredTotalNum = injuredTotalNum.add(injuryPerson);
//                                TaskPbe pbe = new TaskPbe();
//                                pbe.setUuid(UUIDGenerator.getUUID());
//                                pbe.setEarthquakeId(earthquakeId);
//                                pbe.setInfluencefliedId(influenceflieId);
//                                pbe.setPbeId(pbeId);
//                                pbe.setTaskId(taskId);
//                                pbe.setDeathPercent(deathPercent);
//                                pbe.setDeathPerson(deathPersonCount.intValue());
//                                pbe.setInjuryPerson(injuryPerson.intValue());
//                                basicDataService.insertTaskPbe(pbe);
//                            }
//                        }
//                    }
//                }
//                if(dd == 0){
//                    maxDeathPerson = deathTotalNum;
//                    minDeathPerson = deathTotalNum;
//                    maxInjuredPerson = injuredTotalNum;
//                    minInjuredPerson = injuredTotalNum;
//                }
//                ResultDetailsEntity resultDetailsEntity = new ResultDetailsEntity();
//                resultDetailsEntity.setTaskId(taskId);
//                resultDetailsEntity.setLongitude(settingSeismicDetails.get(dd).getLongitude().toString());
//                resultDetailsEntity.setLatitude(settingSeismicDetails.get(dd).getLatitude().toString());
//                resultDetailsEntity.setMagnitude(settingSeismicDetails.get(dd).getEarthquakeLevel());
//                resultDetailsEntity.setDeathToll(String.valueOf(deathTotalNum.intValue()));
//                resultDetailsEntity.setInjuredNum(String.valueOf(injuredTotalNum.intValue()));
//                resultDetailsEntity.setDataSource("2");
//                resultDetailsEntity.setAngle(String.valueOf(settingSeismicDetails.get(dd).getAngle()));
//                resultTotalRepository.updateResultDetailsEntity(resultDetailsEntity);
//
//                if(!settingSeismicDetails.get(dd).getEarthquakeLevel().equals(earthLevel)){
//                    ResultMainEntity resultMainEntity = new ResultMainEntity();
//                    resultMainEntity.setTaskId(taskId);
//                    resultMainEntity.setLongitude(settingSeismicDetails.get(dd-1).getLongitude().toString());
//                    resultMainEntity.setLatitude(settingSeismicDetails.get(dd-1).getLatitude().toString());
//                    resultMainEntity.setMagnitude(settingSeismicDetails.get(dd-1).getEarthquakeLevel());
//                    resultMainEntity.setMagnitude(settingSeismicDetails.get(dd-1).getEarthquakeLevel());
//                    resultMainEntity.setDeathTollBefore(minDeathPerson.compareTo(maxDeathPerson)==0?minDeathPerson.intValue()+"":(minDeathPerson.intValue()+"-"+maxDeathPerson.intValue()));
//                    resultMainEntity.setDeathTollAfter(minDeathPerson.compareTo(maxDeathPerson)==0?minDeathPerson.intValue()+"":(minDeathPerson.intValue()+"-"+maxDeathPerson.intValue()));
//                    resultMainEntity.setInjuredNumBefore(minInjuredPerson.compareTo(maxInjuredPerson)==0?minInjuredPerson.intValue()+"":(minInjuredPerson.intValue()+"-"+maxInjuredPerson.intValue()));
//                    resultMainEntity.setInjuredNumAfter(minInjuredPerson.compareTo(maxInjuredPerson)==0?minInjuredPerson.intValue()+"":(minInjuredPerson.intValue()+"-"+maxInjuredPerson.intValue()));
//                    resultMainEntity.setDataSource("2");
//                    resultTotalRepository.updateResultTotal(resultMainEntity);
//                    maxDeathPerson = deathTotalNum;
//                    minDeathPerson = deathTotalNum;
//                    maxInjuredPerson =  injuredTotalNum;
//                   minInjuredPerson = injuredTotalNum;
//                    earthLevel = settingSeismicDetails.get(dd).getEarthquakeLevel();
//                    System.out.println(resultMainEntity);
//                }
//            }
//            if(deathTotalNum.compareTo(maxDeathPerson)>0){
//                maxDeathPerson = deathTotalNum;
//            }
//            if(deathTotalNum.compareTo(minDeathPerson)<0){
//                minDeathPerson = deathTotalNum;
//            }
//            if(injuredTotalNum.compareTo(maxInjuredPerson)>0){
//                maxInjuredPerson = injuredTotalNum;
//            }
//            if(injuredTotalNum.compareTo(minInjuredPerson)<0){
//                minInjuredPerson = injuredTotalNum;
//            }
//            ResultMainEntity resultMainEntity = new ResultMainEntity();
//            resultMainEntity.setTaskId(taskId);
//            resultMainEntity.setLongitude(detail.getLongitude().toString());
//            resultMainEntity.setLatitude(detail.getLatitude().toString());
//            resultMainEntity.setMagnitude(detail.getEarthquakeLevel());
//            resultMainEntity.setDataSource("2");
//            resultMainEntity.setDeathTollBefore(minDeathPerson.compareTo(maxDeathPerson)==0?minDeathPerson.intValue()+"":(minDeathPerson.intValue()+"-"+maxDeathPerson.intValue()));
//            resultMainEntity.setDeathTollAfter(minDeathPerson.compareTo(maxDeathPerson)==0?minDeathPerson.intValue()+"":(minDeathPerson.intValue()+"-"+maxDeathPerson.intValue()));
//            resultMainEntity.setInjuredNumBefore(minInjuredPerson.compareTo(maxInjuredPerson)==0?minInjuredPerson.intValue()+"":(minInjuredPerson.intValue()+"-"+maxInjuredPerson.intValue()));
//            resultMainEntity.setInjuredNumAfter(minInjuredPerson.compareTo(maxInjuredPerson)==0?minInjuredPerson.intValue()+"":(minInjuredPerson.intValue()+"-"+maxInjuredPerson.intValue()));
//            resultTotalRepository.updateResultTotal(resultMainEntity);
//        }
//        //if(PlatformObjectUtils.isEmpty(resultList)){
//        if(PlatformObjectUtils.isNotEmpty(centerList)){
//            for(CenterResult result: centerList){
//                basicDataService.save(result);
//            }
//        }
//        //}
//        Long end = System.currentTimeMillis();
//        System.out.println("总消耗时间是:"+(end-start)/1000);
//    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResponse savePbeInjuries(String modeId, String taskId) throws Exception {
        RestResponse restResponse = null;
        try {
            if (PlatformObjectUtils.isNotEmpty(redisTemplate.opsForValue().get(taskId))) {
                return RestResponse.fail(503, "该任务的正在被其他人计算，请稍后再操作！！！");
            }
            redisTemplate.opsForValue().set(taskId, "3-2");
            Long start = System.currentTimeMillis();
            casualtyRepository.deleteByTaskId(taskId);

            SeismicIntensityRelation byTaskId = intensityRelationService.getByTaskId(taskId);
            if (byTaskId == null) {
                restResponse = RestResponse.fail(503, "请生成该任务下的地震影响场");
                return restResponse;
            }

            Casualty model = casualtyRepository.getModelById(modeId);
            if (PlatformObjectUtils.isEmpty(model)) {
                restResponse = RestResponse.fail(503, "请选择人员伤亡模型");
                return restResponse;
            }
            @NotNull(message = "计算死亡人数系数不能为空") BigDecimal deathNumber = model.getDeathNumber();
            @NotNull(message = "受伤人数系数不能为空") BigDecimal injuries = model.getInjuries();
            //根据任务id取所有影响场和任务区域的并集，作为最大区域查格网
            List<DataPbeIntStrArea> pbeList = casualtyRepository.getDataPbeIntStrAreaByTaskId(taskId, "4");
            List<DataPbeInjuries> pbeInjuriesList = new ArrayList<>();
            for (DataPbeIntStrArea entity : pbeList) {
                // if ("8db453e667d54473818dcd290aaad3c3".equals(entity.getPbeId())){
                //     System.out.println("");
                // }
                //每个格网的建筑物面积
                BigDecimal area = entity.getCoveredArea();
                BigDecimal population = entity.getPopulation();

                //所有结构的毁坏面积
                BigDecimal totalDanageArea = entity.getHArea().add(entity.getSteelArea()).add(entity.getCArea()).add(entity.getBArea())
                        .add(entity.getBmArea()).add(entity.getSArea()).add(entity.getWArea()).add(entity.getStArea()).add(entity.getOArea());

                //计算死亡比
                BigDecimal deathPercent = BigDecimal.ZERO;
                if (area.compareTo(BigDecimal.ZERO) != 0) {
                    deathPercent = totalDanageArea.divide(area, 8, BigDecimal.ROUND_HALF_UP);
                }
                double pow = Math.pow(deathPercent.doubleValue(), 0.1);
                BigDecimal powBigdeciaml = new BigDecimal(pow);
                BigDecimal subtract = model.getSmrsNumber1().multiply(powBigdeciaml).subtract(model.getSmrsNumber2());
                double log = Math.pow(10, subtract.doubleValue());
                BigDecimal deathRetio = new BigDecimal(log);
                //计算死亡人数
                BigDecimal deathPersonCount = deathNumber.multiply(population).multiply(deathRetio);
                //计算伤亡人数
                BigDecimal injuryNum = deathPersonCount.multiply(injuries);
                DataPbeInjuries pbeInjuries = new DataPbeInjuries();
                pbeInjuries.setId(UUIDGenerator.getUUID()).setPbeId(entity.getPbeId()).setCoveredarea(area)
                        .setPopulation(entity.getPopulation().intValue()).setDeathNum(deathPersonCount.setScale(6, RoundingMode.HALF_UP))
                        .setDeath(deathPercent).setInjuriesNum(injuryNum.setScale(6, RoundingMode.HALF_UP)).setInjuries(injuries)
                        .setDzIntentity(entity.getDzIntensity()).setTaskId(taskId).setGeomText(entity.getGeomText());
                //casualtyRepository.saveDataPbeInjuries(pbeInjuries);
                pbeInjuriesList.add(pbeInjuries);
            }
            System.out.println("开始插入：" + pbeInjuriesList.size());
            //创建data_pbe_injuries 分区
            casualtyRepository.createInjuriesFqRel(taskId);
            //一次10万条
            int fromIndex = 0;
            int toIndex = BATCH_SIZE;
            while (fromIndex != pbeInjuriesList.size()) {
                if (toIndex > pbeInjuriesList.size()) {
                    toIndex = pbeInjuriesList.size();
                }
                List<DataPbeInjuries> list = pbeInjuriesList.subList(fromIndex, toIndex);
                int insertcount = casualtyRepository.savepbeInjuriesList(list);
                System.out.println("插入成功" + insertcount);
                fromIndex = toIndex;
                toIndex += BATCH_SIZE;
                if (toIndex > pbeInjuriesList.size())
                    toIndex = pbeInjuriesList.size();
            }
            byTaskId.setButton2_status2("1");
            byTaskId.setModel2Id(modeId);
            byTaskId.setButton2_status3("0");
            intensityRelationService.updateSeismicIntensityRelation(byTaskId);
            System.out.println("保存格网时间花费" + (System.currentTimeMillis() - start) / 1000);

            return ResponseCreator.createSuccessResponse("计算成功!");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("计算失败!");
            return restResponse;
        } finally {
            redisTemplate.delete(taskId);
            if (restResponse != null) {
                if (restResponse.getCode() != 200) {
                    //事务手动回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse countIntensityAndStructureOfArea(String taskId, String tab,String range) {
        RestResponse restResponse = null;
        try {
            if (PlatformObjectUtils.isNotEmpty(redisTemplate.opsForValue().get(taskId))) {
                redisTemplate.opsForValue().get(taskId);
                return RestResponse.fail(503, "该任务的正在被其他人计算，请稍后再操作！！！");
            }
            redisTemplate.opsForValue().set(taskId, "3-1");

            Long start = System.currentTimeMillis();
            //删除taskId上一次计算的结果
            casualtyRepository.deleteDataPbeIntStrAreaByTaskId(taskId);
            //查询到任务和模型关联的模型信息
            SeismicIntensityRelation byTaskId = intensityRelationService.getByTaskId(taskId);
            if (byTaskId == null) {
                restResponse = RestResponse.fail(503, "请生成该任务下的地震影响场");
                return restResponse;
            }
            PreAssessTaskEntity byId = preAssessTaskService.getById(taskId);
            String taskDistrict = byId.getTaskDistrict();

            String province = "";//省
            String city = "";//市
            String country = "";//县
            String town = "";//镇
            StructuralProportionVo structuralProportion = null;//人口与建筑物数据的VO
            Map<String, List<VulnerabilityVO>> listMap = new HashMap<>();//key:地震烈度；value:建筑物易损性信息VO
            List<BuildingVulnerability> allVulnerability = new ArrayList<>();//建筑物易损性信息
            //0:任务范围内的格网；1:任务范围外，影响场范围内的格网
            List<PbeEntity> pbeList = null;
            //格网数据
            List<DataPbeIntStrArea> pbeIntStrAreaList = new ArrayList<>();
            //0:任务范围内的格网；1:任务范围外，影响场范围内的格网
            for (int k = 0; k < 2; k++) {
                if (range.equals("1") && k > 0) {
                    break;  // 如果 range 是 "1"，跳出外层循环，保证只执行一次
                }
                pbeList = casualtyRepository.getAllPbeByTaskId(taskId, k,range);
                System.out.println(pbeList.size());
                if (PlatformObjectUtils.isEmpty(pbeList) && k == 0) {
                    restResponse = RestResponse.fail(503, "请先上传该任务区域的格网数据！");
                    return restResponse;
                }
                for (PbeEntity pbeEntity : pbeList) {
                    // if ("9ea1ad6b1d2e4c2f9e9d97812c1c3133".equals(pbeEntity.getPbeId())){
                    //     System.out.println("");
                    // }
                    //每个格网的建筑物面积
                    BigDecimal area = BigDecimal.valueOf(pbeEntity.getCoveredarea());

                    //获取格网下不同建筑物所占比例
                    BigDecimal hRatio = new BigDecimal(0);
                    BigDecimal steelRatio = new BigDecimal(0);
                    BigDecimal cRatio = new BigDecimal(0);
                    BigDecimal bRatio = new BigDecimal(0);
                    BigDecimal bmRatio = new BigDecimal(0);
                    BigDecimal sRatio = new BigDecimal(0);
                    BigDecimal wRatio = new BigDecimal(0);
                    BigDecimal stRatio = new BigDecimal(0);
                    BigDecimal oRatio = new BigDecimal(0);
                    //住宅房屋占比（%）
                    BigDecimal dhpHouseTatio = BigDecimal.ZERO;
                    if ("1".equals(pbeEntity.getJglxType())) {
                        hRatio = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxGcjz()) ? "0" : pbeEntity.getJglxGcjz()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                        steelRatio = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxGjg()) ? "0" : pbeEntity.getJglxGjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                        cRatio = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxDcgjhntjg()) ? "0" : pbeEntity.getJglxDcgjhntjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                        bRatio = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxZhjg()) ? "0" : pbeEntity.getJglxZhjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                        bmRatio = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxZmjg()) ? "0" : pbeEntity.getJglxZmjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                        sRatio = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxTjg()) ? "0" : pbeEntity.getJglxTjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                        wRatio = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxMjg()) ? "0" : pbeEntity.getJglxMjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                        stRatio = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxSjg()) ? "0" : pbeEntity.getJglxSjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                        oRatio = new BigDecimal(PlatformObjectUtils.isEmpty(pbeEntity.getJglxQtjg()) ? "0" : pbeEntity.getJglxQtjg()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP);
                        dhpHouseTatio = new BigDecimal(pbeEntity.getZzfwzb());
                    } else {
                        //同一个省市县镇只查一次
                        if (!pbeEntity.getProvince().equals(province) || !pbeEntity.getCity().equals(city) || !pbeEntity.getCounty().equals(country) || !town.equals(pbeEntity.getTown())) {
                            structuralProportion = preAssessResultService.getStructuralProportion(pbeEntity.getProvince(),
                                    pbeEntity.getCity(), pbeEntity.getCounty(), pbeEntity.getTown(), pbeEntity.getTownorcontry());
                        } else {
                            if (PlatformObjectUtils.isEmpty(structuralProportion)) {
                                structuralProportion = preAssessResultService.getStructuralProportion(pbeEntity.getProvince(),
                                        pbeEntity.getCity(), pbeEntity.getCounty(), pbeEntity.getTown(), pbeEntity.getTownorcontry());
                            }
                        }
                        //此时人口与建筑物为空，则区县级的人口与建筑物为空
                        if (PlatformObjectUtils.isEmpty(structuralProportion)) {
                            //tab1为true表示该格网在该任务区域内
                            boolean tab1 = false;
                            for (String s : taskDistrict.split("、")) {
                                if (s.equals(pbeEntity.getProvince() + "-" + pbeEntity.getCity() + "-" + pbeEntity.getCounty())) {
                                    tab1 = true;
                                    break;
                                } else if (s.equals(pbeEntity.getProvince() + "-" + pbeEntity.getCity())) {
                                    tab1 = true;
                                    break;
                                } else if (s.equals(pbeEntity.getProvince())) {
                                    tab1 = true;
                                    break;
                                }
                            }
                            if (tab1 && k == 0) {
                                restResponse = RestResponse.fail(503,
                                        "未获取到" + pbeEntity.getProvince() + "、" + pbeEntity.getCity() + "、" + pbeEntity.getCounty() + "的人口和建筑物概况数据！");
                                return restResponse;
                            } else if ((!tab1 && k == 0 && !tab.contains("1")) || k == 1 && !tab.contains("1")) {
                              if (range.equals("0")){
                                  JSONObject map = new JSONObject();
                                map.put("tab", tab + "1");
                                restResponse = RestResponse.fail(501, "未获取到" + pbeEntity.getProvince() + "、" + pbeEntity.getCity() +
                                        "、" + pbeEntity.getCounty() + "的人口和建筑物概况数据,请确认是否继续进行计算！", map);
                                return restResponse;
                              }
                            }
                        }
                        if ("城镇".equals(pbeEntity.getTownorcontry())) {
                            hRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpTownHighTatio();
                            steelRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpTownSteelTatio();
                            cRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpTownBetonTatio();
                            bRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpTownBrickTatio();
                            bmRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpTownMasonryTatio();
                            sRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpTownSoilTatio();
                            wRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpTownWoodTatio();
                            stRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpTownStoneTatio();
                            oRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpTownOtherTatio();
                        } else if ("农村".equals(pbeEntity.getTownorcontry())) {
                            hRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpVillageHighTatio();
                            steelRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpVillageSteelTatio();
                            cRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpVillageBetonTatio();
                            bRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpVillageBrickTatio();
                            bmRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpVillageMasonryTatio();
                            sRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpVillageSoilTatio();
                            wRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpVillageWoodTatio();
                            stRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpVillageStoneTatio();
                            oRatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpVillageOtherTatio();
                        }
                        dhpHouseTatio = structuralProportion == null ? BigDecimal.ZERO : structuralProportion.getDhpHouseTatio();
                    }
                    BigDecimal hArea = area.multiply(hRatio);
                    //钢结构 0.1
                    BigDecimal steelArea = area.multiply(steelRatio);
                    //多层钢筋混凝土结构 0.2
                    BigDecimal cArea = area.multiply(cRatio);
                    //砖混结构 0.15
                    BigDecimal bArea = area.multiply(bRatio);
                    //砖木结构 0.15
                    BigDecimal bmArea = area.multiply(bmRatio);
                    //土结构 0.15
                    BigDecimal sArea = area.multiply(sRatio);
                    //木结构 0.1
                    BigDecimal wArea = area.multiply(wRatio);
                    //石结构 0.1
                    BigDecimal stArea = area.multiply(stRatio);
                    //其他结构 0.05
                    BigDecimal oArea = area.multiply(oRatio);

                    //每个省市县只查询一次数据库
                    if (!pbeEntity.getProvince().equals(province) || !pbeEntity.getCity().equals(city) || !pbeEntity.getCounty().equals(country)) {
                        allVulnerability = buildingVulnerabilityService.getAllVulnerabilityOrder(pbeEntity.getProvince(),
                                pbeEntity.getCity(), pbeEntity.getCounty(), "1");
                        //改造allVulnerability
                        Map<String, Object> rebuild = rebuild(allVulnerability);
                        if (!rebuild.get("code").equals("200")) {
                            restResponse = RestResponse.fail(503, String.valueOf(rebuild.get("msg")));
                            return restResponse;
                        }
                        listMap = (Map<String, List<VulnerabilityVO>>) rebuild.get("listMap");
                    } else {
                        if (PlatformObjectUtils.isEmpty(allVulnerability)) {
                            allVulnerability = buildingVulnerabilityService.getAllVulnerabilityOrder(pbeEntity.getProvince(), pbeEntity.getCity(), pbeEntity.getCounty(), "1");
                            //改造allVulnerability
                            Map<String, Object> rebuild = rebuild(allVulnerability);
                            if (!rebuild.get("code").equals("200")) {
                                restResponse = RestResponse.fail(503, String.valueOf(rebuild.get("msg")));
                                return restResponse;
                            }
                            listMap = (Map<String, List<VulnerabilityVO>>) rebuild.get("listMap");
                        }
                    }
                    if (PlatformObjectUtils.isEmpty(allVulnerability)) {
                        //tab1为true表示该格网在该任务区域内
                        boolean tab1 = false;
                        for (String s : taskDistrict.split("、")) {
                            if (s.equals(pbeEntity.getProvince() + "-" + pbeEntity.getCity() + "-" + pbeEntity.getCounty())) {
                                tab1 = true;
                                break;
                            } else if (s.equals(pbeEntity.getProvince() + "-" + pbeEntity.getCity())) {
                                tab1 = true;
                                break;
                            } else if (s.equals(pbeEntity.getProvince())) {
                                tab1 = true;
                                break;
                            }
                        }
                        if (tab1 && k == 0) {
                            restResponse = RestResponse.fail(503, "未获取到" + pbeEntity.getProvince() + "、" + pbeEntity.getCity() +
                                    "、" + pbeEntity.getCounty() + "的建筑物易损性数据，请到【统计数据管理-建筑物易损性数据】菜单中维护！");
                            return restResponse;
                        } else if ((!tab1 && k == 0 && !tab.contains("2")) || k == 1 && !tab.contains("2")) {
                            if (range.equals("0")){
                                JSONObject map = new JSONObject();
                                map.put("tab", tab + "2");
                                restResponse = RestResponse.fail(501, "在影响场范围内" + pbeEntity.getProvince() + "、" + pbeEntity.getCity() +
                                        "、" + pbeEntity.getCounty() + "的建筑物易损性数据未维护，请确认是否继续计算？", map);
                                return restResponse;
                            }
                        }
                        // return RestResponse.fail("未获取到" + pbeEntity.getProvince() + "、" + pbeEntity.getCity() + "、" + pbeEntity.getCounty() + "的建筑物易损性数据，请到【统计数据管理-建筑物易损性数据】菜单中维护！");
                    }
                    for (int i = 6; i < 11; i++) {
                        if (PlatformObjectUtils.isNotEmpty(allVulnerability)) {
                            List<VulnerabilityVO> vulnerabilityVOS = listMap.get(String.valueOf(i));
                            for (VulnerabilityVO vo : vulnerabilityVOS) {
                                BigDecimal thArea = vo.getZero() == null ? BigDecimal.ZERO : hArea.multiply(vo.getZero());
                                BigDecimal tsteelArea = vo.getOne() == null ? BigDecimal.ZERO : steelArea.multiply(vo.getOne());
                                BigDecimal tcArea = vo.getTwo() == null ? BigDecimal.ZERO : cArea.multiply(vo.getTwo());
                                BigDecimal tbArea = vo.getThree() == null ? BigDecimal.ZERO : bArea.multiply(vo.getThree());
                                BigDecimal tbmArea = vo.getFour() == null ? BigDecimal.ZERO : bmArea.multiply(vo.getFour());
                                BigDecimal tsArea = vo.getFive() == null ? BigDecimal.ZERO : sArea.multiply(vo.getFive());
                                BigDecimal twArea = vo.getSix() == null ? BigDecimal.ZERO : wArea.multiply(vo.getSix());
                                BigDecimal tstArea = vo.getSeven() == null ? BigDecimal.ZERO : stArea.multiply(vo.getSeven());
                                BigDecimal toArea = vo.getEight() == null ? BigDecimal.ZERO : oArea.multiply(vo.getEight());
                                DataPbeIntStrArea pbeIntStrArea = new DataPbeIntStrArea();

                                pbeIntStrArea.setId(UUIDGenerator.getUUID()).setPbeId(pbeEntity.getPbeId())
                                        .setDzIntensity(String.valueOf(i)).setTaskId(taskId).setGeomText(pbeEntity.getGeomText())
                                        .setHArea(thArea).setSteelArea(tsteelArea).setCArea(tcArea).setBArea(tbArea).setBmArea(tbmArea)
                                        .setSArea(tsArea).setWArea(twArea).setStArea(tstArea).setOArea(toArea)
                                        .setDestroy(vo.getDestroy()).setPopulation(BigDecimal.valueOf(pbeEntity.getPopulation()))
                                        .setCoveredArea(area).setTownorcontry(pbeEntity.getTownorcontry()).setProvince(pbeEntity.getProvince())
                                        .setCity(pbeEntity.getCity()).setCounty(pbeEntity.getCounty()).setTown(pbeEntity.getTown())
                                        .setDhpHouseTatio(dhpHouseTatio).setType1(String.valueOf(k));
                                pbeIntStrAreaList.add(pbeIntStrArea);
                                //casualtyRepository.saveDataPbeIntStrArea(pbeIntStrArea);
                            }
                        } else {
                            for (int j = 0; j < 5; j++) {
                                DataPbeIntStrArea pbeIntStrArea = new DataPbeIntStrArea();
                                pbeIntStrArea.setId(UUIDGenerator.getUUID()).setPbeId(pbeEntity.getPbeId())
                                        .setDzIntensity(String.valueOf(i)).setTaskId(taskId).setGeomText(pbeEntity.getGeomText())
                                        .setHArea(BigDecimal.ZERO).setSteelArea(BigDecimal.ZERO).setCArea(BigDecimal.ZERO).setBArea(BigDecimal.ZERO).setBmArea(BigDecimal.ZERO)
                                        .setSArea(BigDecimal.ZERO).setWArea(BigDecimal.ZERO).setStArea(BigDecimal.ZERO).setOArea(BigDecimal.ZERO)
                                        .setDestroy(String.valueOf(j)).setPopulation(BigDecimal.valueOf(pbeEntity.getPopulation()))
                                        .setCoveredArea(area).setTownorcontry(pbeEntity.getTownorcontry()).setProvince(pbeEntity.getProvince())
                                        .setCity(pbeEntity.getCity()).setCounty(pbeEntity.getCounty()).setTown(pbeEntity.getTown())
                                        .setDhpHouseTatio(dhpHouseTatio).setType1(String.valueOf(k));
                                pbeIntStrAreaList.add(pbeIntStrArea);
                                //casualtyRepository.saveDataPbeIntStrArea(pbeIntStrArea);
                            }
                        }
                    }
                    province = pbeEntity.getProvince();
                    city = pbeEntity.getCity();
                    country = pbeEntity.getCounty();
                    town = pbeEntity.getTown();
                }
            }
            System.out.println(pbeIntStrAreaList.size() + "开始插入");
            //生成分区表
            casualtyRepository.createFqRel(taskId);

            //一次10万条
            int fromIndex = 0;
            int toIndex = BATCH_SIZE;
            while (fromIndex != pbeIntStrAreaList.size()) {
                if (toIndex > pbeIntStrAreaList.size()) {
                    toIndex = pbeIntStrAreaList.size();
                }
                List<DataPbeIntStrArea> list = pbeIntStrAreaList.subList(fromIndex, toIndex);
                int insertcount = casualtyRepository.batchupdate(list);
                fromIndex = toIndex;
                toIndex += BATCH_SIZE;
                if (toIndex > pbeIntStrAreaList.size())
                    toIndex = pbeIntStrAreaList.size();
            }

            byTaskId.setButton2_status1("1");
            byTaskId.setButton2_status2("0");
            byTaskId.setButton2_status3("0");
            byTaskId.setButton3_status1("0");
            byTaskId.setButton3_status2("0");
            if ("1".equals(byTaskId.getModel4Type())) {
                byTaskId.setButton4_status1("0");
                byTaskId.setButton4_status2("0");
            }
            byTaskId.setButton6_status1("0");
            intensityRelationService.updateSeismicIntensityRelation(byTaskId);

            System.out.println("保存格网时间花费" + (System.currentTimeMillis() - start) / 1000);
            return ResponseCreator.createSuccessResponse("计算成功!");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("计算失败!");
            return restResponse;
        } finally {
            redisTemplate.delete(taskId);
            if (restResponse != null) {
                if (restResponse.getCode() != 200) {
                    //事务手动回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResponse calculate(String taskId,String range) {
        RestResponse restResponse = null;
        try {
            if (PlatformObjectUtils.isNotEmpty(redisTemplate.opsForValue().get(taskId))) {
                return RestResponse.fail(503, "该任务的正在被其他人计算，请稍后再操作！！！");
            }
            redisTemplate.opsForValue().set(taskId, "3-3");
            Long start = System.currentTimeMillis();

            SeismicIntensityRelation byTaskId = intensityRelationService.getByTaskId(taskId);
            if (byTaskId == null) {
                return RestResponse.fail(503, "请生成该任务下的地震影响场");
            }

            //通过任务id获取到所有点的详情
            List<String> pointDetailList = settingSeismicService.getPointDetailByTaskId(taskId);
            //根据任务id获取任务下的所有的影响场（椭圆）下的同一个地震烈度的格网的人员伤亡数据
            //----根据任务id获取任务下的所有的影响场（椭圆）下的同一个地震烈度的格网的人员伤亡数据 0
            // 或者据任务id获取任务下 任务范围与影响场相交范围的同一个地震烈度的格网的人员伤亡数据-----1-------------------------------------------
            List<Map<String, Object>> mapList = casualtyRepository.getPbeInjuriesByTaskId(taskId,range);
            //pbeId,area,deathNum,injuriesNum,longitude,latitude,earthquakeLevel,angle,earthquakeId
            if (PlatformObjectUtils.isEmpty(mapList)) {
                // casualtyRepository.deleteByTaskId(taskId);
                return RestResponse.fail(503, "计算失败,该任务尚未生成影响场!");
            }
            //获取到同一个设定地震点下不同影响场的最大相交面积的格网的数据
            Map<String, Map<String, Object>> initMap = initMap1(mapList);
            Map<String, BigDecimal[]> detailMap = new HashMap<>();
            for (Map.Entry<String, Map<String, Object>> entry : initMap.entrySet()) {
                Map<String, Object> value = entry.getValue();
                //详表
                BigDecimal[] objects = null;
                String key1 = taskId + "-" + value.get("sort") + "-" + value.get("earthquakeLevel") + "-" + value.get("angle");
                if (detailMap.containsKey(key1)) {
                    objects = detailMap.get(key1);
                    objects[0] = objects[0].add(BigDecimal.valueOf((Float) value.get("deathNum")));//受伤人数和
                    objects[1] = objects[1].add(BigDecimal.valueOf((Float) value.get("injuriesNum")));//死亡人数和
                } else {
                    //初始化
                    objects = new BigDecimal[2];
                    objects[0] = BigDecimal.valueOf((Float) value.get("deathNum"));
                    objects[1] = BigDecimal.valueOf((Float) value.get("injuriesNum"));
                }
                detailMap.put(key1, objects);
            }
            List<ResultDetailsEntity> resultDetailsEntityList = new ArrayList<>();
            Map<String, ResultMainEntity> map = new HashMap<>();
            for (String key : pointDetailList) {
                String[] split = key.split("-");
                ResultDetailsEntity detailsEntity = new ResultDetailsEntity();
                detailsEntity.setTaskId(split[0]);
                detailsEntity.setSort(split[1]);
                detailsEntity.setMagnitude(new BigDecimal(split[2]+""));
                detailsEntity.setAngle(split[3]);

                BigDecimal deathToll = BigDecimal.ZERO;
                BigDecimal injuredNum = BigDecimal.ZERO;
                BigDecimal[] value = detailMap.get(key);
                if (value != null && value.length > 0) {
                    deathToll = value[0].setScale(0, RoundingMode.HALF_UP);
                    injuredNum = value[1].setScale(0, RoundingMode.HALF_UP);
                }
                detailsEntity.setDeathToll(String.valueOf(deathToll));
                detailsEntity.setInjuredNum(String.valueOf(injuredNum));
                detailsEntity.setUpdateId(PlatformSessionUtils.getUserId());
                detailsEntity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                detailsEntity.setDataSource("2");
                resultDetailsEntityList.add(detailsEntity);
                resultTotalService.updateResultDetailsEntity(detailsEntity);

                //结果主表
                String key2 = split[0] + "-" + split[1] + "-" + split[2];
                ResultMainEntity resultMainEntity = null;
                if (map.containsKey(key2)) {
                    resultMainEntity = map.get(key2);
                    resultMainEntity.setDeathTollBefore(compareTo(deathToll, resultMainEntity.getDeathTollBefore()));
                    resultMainEntity.setInjuredNumBefore(compareTo(injuredNum, resultMainEntity.getInjuredNumBefore()));

                } else {
                    resultMainEntity = new ResultMainEntity();
                    resultMainEntity.setDeathTollBefore(deathToll + "-0");
                    resultMainEntity.setInjuredNumBefore(injuredNum + "-0");
                    map.put(key2, resultMainEntity);
                }
                map.put(key2, resultMainEntity);
            }
            // for (Map.Entry<String, BigDecimal[]> entry : detailMap.entrySet()) {
            //     String[] split = entry.getKey().split("-");
            //     ResultDetailsEntity detailsEntity = new ResultDetailsEntity();
            //     detailsEntity.setTaskId(split[0]);
            //     detailsEntity.setLongitude(split[1]);
            //     detailsEntity.setLatitude(split[2]);
            //     detailsEntity.setMagnitude(new BigDecimal(split[3]));
            //     detailsEntity.setAngle(split[4]);
            //
            //     BigDecimal[] value = entry.getValue();
            //     BigDecimal deathToll = value[0].setScale(0, RoundingMode.HALF_UP);
            //     BigDecimal injuredNum = value[1].setScale(0, RoundingMode.HALF_UP);
            //     detailsEntity.setDeathToll(String.valueOf(deathToll));
            //     detailsEntity.setInjuredNum(String.valueOf(injuredNum));
            //
            //     detailsEntity.setUpdateId(PlatformSessionUtils.getUserId());
            //     detailsEntity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
            //     detailsEntity.setDataSource("2");
            //     resultDetailsEntityList.add(detailsEntity);
            //     resultTotalService.updateResultDetailsEntity(detailsEntity);
            //
            //     //结果主表
            //     String key2 = split[0] + "-" + split[1] + "-" + split[2] + "-" + split[3];
            //     ResultMainEntity resultMainEntity = null;
            //     if (map.containsKey(key2)) {
            //         resultMainEntity = map.get(key2);
            //         resultMainEntity.setDeathTollBefore(compareTo(deathToll, resultMainEntity.getDeathTollBefore()));
            //         resultMainEntity.setInjuredNumBefore(compareTo(injuredNum, resultMainEntity.getInjuredNumBefore()));
            //
            //     } else {
            //         resultMainEntity = new ResultMainEntity();
            //         resultMainEntity.setDeathTollBefore(deathToll + "-0");
            //         resultMainEntity.setInjuredNumBefore(injuredNum + "-0");
            //         map.put(key2, resultMainEntity);
            //     }
            //     map.put(key2, resultMainEntity);
            // }
            System.out.println("更新resultDetailsEntityList共：" + resultDetailsEntityList.size());

            System.out.println(map.size());
            resultTotalService.updateResultMainEntity(map, "5");

            byTaskId.setButton2_status3("1");
            intensityRelationService.updateSeismicIntensityRelation(byTaskId);
            System.out.println("计算格网时间花费" + (System.currentTimeMillis() - start) / 1000);
            return RestResponse.succeed("计算成功!");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("计算失败!");
            return restResponse;
        } finally {
            redisTemplate.delete(taskId);
            if (restResponse != null) {
                if (restResponse.getCode() != 200) {
                    //事务手动回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            }
        }
    }

    private Map<String, Map<String, Object>> initMap1(List<Map<String, Object>> mapList) {
        //pbeId,area,deathNum,injuriesNum,longitude,latitude,earthquakeLevel,angle,earthquakeId
        Map<String, Map<String, Object>> initMap = new HashMap<>();
        for (Map<String, Object> map1 : mapList) {
            String key = map1.get("pbeId") + "-" + map1.get("earthquakeId");
            if (initMap.containsKey(key)) {
                Map<String, Object> map2 = initMap.get(key);
                if (((Double) map2.get("area")).compareTo((Double) map1.get("area")) < 0) {
                    initMap.put(key, map1);
                } else if (((Double) map2.get("area")).compareTo((Double) map1.get("area")) == 0) {
                    if (((BigDecimal) map2.get("earthquakeLevel")).compareTo((BigDecimal) map1.get("earthquakeLevel")) < 0) {
                        initMap.put(key, map1);
                    }
                }
            } else {
                initMap.put(key, map1);
            }
        }
        return initMap;
    }

    private String compareTo(BigDecimal num1, String num2) {
        // num1:5 8 4 3
        // num2:10-0
        String[] split = num2.split("-");//5 10
        for (int i = 0; i < split.length; i++) {
            if (i == 0 && num1.compareTo(new BigDecimal(split[0])) < 0) {
                if (split.length == 2) {
                    if (new BigDecimal(split[0]).compareTo(new BigDecimal(split[1])) > 0) {
                        split[1] = String.valueOf(new BigDecimal(split[0]).setScale(0, RoundingMode.HALF_UP));
                        split[0] = String.valueOf(num1.setScale(0, RoundingMode.HALF_UP));
                    } else {
                        split[0] = String.valueOf(num1.setScale(0, RoundingMode.HALF_UP));
                        split[1] = String.valueOf(new BigDecimal(split[1]).setScale(0, RoundingMode.HALF_UP));
                    }
                } else {
                    split[0] = String.valueOf(num1.setScale(0, RoundingMode.HALF_UP));
                    split[1] = String.valueOf(new BigDecimal(split[1]).setScale(0, RoundingMode.HALF_UP));
                }
            } else if (i == 1 && num1.compareTo(new BigDecimal(split[1])) > 0) {
                split[0] = String.valueOf(new BigDecimal(split[0]).setScale(0, RoundingMode.HALF_UP));
                split[1] = String.valueOf(num1.setScale(0, RoundingMode.HALF_UP));
            }
        }
        num2 = split[0] + "-" + split[1];
        return num2;
    }

    /**
     * @param allVulnerability
     * @return code
     * listMap key:烈度
     * values:每个破坏程度的每个结构类型的破坏比例
     * 结构类型
     * 0高层建筑
     * 1钢结构
     * 2多层钢筋混凝土结构
     * 3砖混结构
     * 4砖木结构
     * 5土结构
     * 6木结构
     * 7石结构
     * 8其他结构
     */
    private Map<String, Object> rebuild(List<BuildingVulnerability> allVulnerability) {
        Map<String, Object> map = null;
        List<String> list = new ArrayList<>();//存储 结构类型+破坏程度，用以判断是否重复
        Map<String, List<VulnerabilityVO>> listMap = new HashMap<>();
        List<VulnerabilityVO> voList1 = null;
        List<VulnerabilityVO> voList2 = null;
        List<VulnerabilityVO> voList3 = null;
        List<VulnerabilityVO> voList4 = null;
        List<VulnerabilityVO> voList5 = null;
        BuildingVulnerability buildingVulnerability1 = null;
        BuildingVulnerability buildingVulnerability2 = null;
        BuildingVulnerability buildingVulnerability3 = null;
        BuildingVulnerability buildingVulnerability4 = null;
        BuildingVulnerability buildingVulnerability5 = null;
        BuildingVulnerability buildingVulnerability6 = null;
        BuildingVulnerability buildingVulnerability7 = null;
        BuildingVulnerability buildingVulnerability8 = null;
        BuildingVulnerability buildingVulnerability9 = null;
        for (int i = 0; i < allVulnerability.size(); ) {
            // 获取第i个结构类型的建筑物易损性数据
            buildingVulnerability1 = allVulnerability.get(i);
            //是否存在地震烈度
            if (listMap.containsKey("6")) {
                voList1 = listMap.get("6");
            } else {
                voList1 = new ArrayList<>();
            }
            VulnerabilityVO vo = new VulnerabilityVO();
            //破坏程度
            String destroy = buildingVulnerability1.getDestroy();
            vo.setDestroy(destroy);
            //判断第i个建筑物易损性数据是否是高层结构
            if ("0".equals(buildingVulnerability1.getStructureType())) {
                //判断是否有重复的结构类型-地震烈度-破坏程度
                map = isRepeat(list, "6", buildingVulnerability1.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                //高层结构烈度为6的破坏比例
                vo.setZero(buildingVulnerability1.getSix());
                //则i下标+1
                i++;
            }
            if (i == allVulnerability.size()) {
                buildingVulnerability2 = new BuildingVulnerability();
            } else {
                // 获取第i个结构类型的建筑物易损性数据
                buildingVulnerability2 = allVulnerability.get(i);
            }
            //判断第i个建筑物易损性数据是否是钢结构
            if ("1".equals(buildingVulnerability2.getStructureType())) {
                //判断是否有重复的结构类型-地震烈度-破坏程度
                map = isRepeat(list, "6", buildingVulnerability2.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                //钢结构烈度为6的破坏比例
                vo.setOne(buildingVulnerability2.getSix());
                //则i下标+1
                i++;
            }
            if (i == allVulnerability.size()) {
                buildingVulnerability3 = new BuildingVulnerability();
            } else {
                // 获取第i个结构类型的建筑物易损性数据
                buildingVulnerability3 = allVulnerability.get(i);
            }
            if ("2".equals(buildingVulnerability3.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability3.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setTwo(buildingVulnerability3.getSix());
                i++;
            }
            if (i == allVulnerability.size()) {
                buildingVulnerability4 = new BuildingVulnerability();
            } else {
                // 获取第i个结构类型的建筑物易损性数据
                buildingVulnerability4 = allVulnerability.get(i);
            }
            if ("3".equals(buildingVulnerability4.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability4.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setThree(buildingVulnerability4.getSix());
                i++;
            }
            if (i == allVulnerability.size()) {
                buildingVulnerability5 = new BuildingVulnerability();
            } else {
                // 获取第i个结构类型的建筑物易损性数据
                buildingVulnerability5 = allVulnerability.get(i);
            }
            if ("4".equals(buildingVulnerability5.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability5.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFour(buildingVulnerability5.getSix());
                i++;
            }
            if (i == allVulnerability.size()) {
                buildingVulnerability6 = new BuildingVulnerability();
            } else {
                // 获取第i个结构类型的建筑物易损性数据
                buildingVulnerability6 = allVulnerability.get(i);
            }
            if ("5".equals(buildingVulnerability6.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability6.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFive(buildingVulnerability6.getSix());
                i++;
            }
            if (i == allVulnerability.size()) {
                buildingVulnerability7 = new BuildingVulnerability();
            } else {
                // 获取第i个结构类型的建筑物易损性数据
                buildingVulnerability7 = allVulnerability.get(i);
            }
            if ("6".equals(buildingVulnerability7.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability7.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setSix(buildingVulnerability7.getSix());
                i++;
            }
            if (i == allVulnerability.size()) {
                buildingVulnerability8 = new BuildingVulnerability();
            } else {
                // 获取第i个结构类型的建筑物易损性数据
                buildingVulnerability8 = allVulnerability.get(i);
            }
            if ("7".equals(buildingVulnerability8.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability8.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setSeven(buildingVulnerability8.getSix());
                i++;
            }
            if (i == allVulnerability.size()) {
                buildingVulnerability9 = new BuildingVulnerability();
            } else {
                // 获取第i个结构类型的建筑物易损性数据
                buildingVulnerability9 = allVulnerability.get(i);
            }
            if ("8".equals(buildingVulnerability9.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability9.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setEight(buildingVulnerability9.getSix());
                i++;
            }
            voList1.add(vo);
            listMap.put("6", voList1);

            if (listMap.containsKey("7")) {
                voList2 = listMap.get("7");
            } else {
                voList2 = new ArrayList<>();
            }
            vo = new VulnerabilityVO();
            vo.setDestroy(destroy);
            if ("0".equals(buildingVulnerability1.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability1.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setZero(buildingVulnerability1.getSeven());
            }
            if ("1".equals(buildingVulnerability2.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability2.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setOne(buildingVulnerability2.getSeven());
            }
            if ("2".equals(buildingVulnerability3.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability3.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setTwo(buildingVulnerability3.getSeven());
            }
            if ("3".equals(buildingVulnerability4.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability4.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setThree(buildingVulnerability4.getSeven());
            }
            if ("4".equals(buildingVulnerability5.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability5.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFour(buildingVulnerability5.getSeven());
            }
            if ("5".equals(buildingVulnerability6.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability6.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFive(buildingVulnerability6.getSeven());
            }
            if ("6".equals(buildingVulnerability7.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability7.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setSix(buildingVulnerability7.getSeven());
            }
            if ("7".equals(buildingVulnerability8.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability8.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setSeven(buildingVulnerability8.getSeven());
            }
            if ("8".equals(buildingVulnerability9.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability9.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setEight(buildingVulnerability9.getSeven());
            }
            voList2.add(vo);
            listMap.put("7", voList2);

            if (listMap.containsKey("8")) {
                voList3 = listMap.get("8");
            } else {
                voList3 = new ArrayList<>();
            }
            vo = new VulnerabilityVO();
            vo.setDestroy(destroy);
            if ("0".equals(buildingVulnerability1.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability1.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setZero(buildingVulnerability1.getEight());
            }
            if ("1".equals(buildingVulnerability2.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability2.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setOne(buildingVulnerability2.getEight());
            }
            if ("2".equals(buildingVulnerability3.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability3.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setTwo(buildingVulnerability3.getEight());
            }
            if ("3".equals(buildingVulnerability4.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability4.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setThree(buildingVulnerability4.getEight());
            }
            if ("4".equals(buildingVulnerability5.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability5.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFour(buildingVulnerability5.getEight());
            }
            if ("5".equals(buildingVulnerability6.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability6.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFive(buildingVulnerability6.getEight());
            }
            if ("6".equals(buildingVulnerability7.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability7.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setSix(buildingVulnerability7.getEight());
            }
            if ("7".equals(buildingVulnerability8.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability8.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setSeven(buildingVulnerability8.getEight());
            }
            if ("8".equals(buildingVulnerability9.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability9.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setEight(buildingVulnerability9.getEight());
            }
            voList3.add(vo);
            listMap.put("8", voList3);

            if (listMap.containsKey("9")) {
                voList4 = listMap.get("9");
            } else {
                voList4 = new ArrayList<>();
            }
            vo = new VulnerabilityVO();
            vo.setDestroy(destroy);
            if ("0".equals(buildingVulnerability1.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability1.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setZero(buildingVulnerability1.getNine());
            }
            if ("1".equals(buildingVulnerability2.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability2.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setOne(buildingVulnerability2.getNine());
            }
            if ("2".equals(buildingVulnerability3.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability3.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setTwo(buildingVulnerability3.getNine());
            }
            if ("3".equals(buildingVulnerability4.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability4.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setThree(buildingVulnerability4.getNine());
            }
            if ("4".equals(buildingVulnerability5.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability5.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFour(buildingVulnerability5.getNine());
            }
            if ("5".equals(buildingVulnerability6.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability6.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFive(buildingVulnerability6.getNine());
            }
            if ("6".equals(buildingVulnerability7.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability7.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setSix(buildingVulnerability7.getNine());
            }
            if ("7".equals(buildingVulnerability8.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability8.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setSeven(buildingVulnerability8.getNine());
            }
            if ("8".equals(buildingVulnerability9.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability9.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setEight(buildingVulnerability9.getNine());
            }
            voList4.add(vo);
            listMap.put("9", voList4);

            if (listMap.containsKey("10")) {
                voList5 = listMap.get("10");
            } else {
                voList5 = new ArrayList<>();
            }
            vo = new VulnerabilityVO();
            vo.setDestroy(destroy);
            if ("0".equals(buildingVulnerability1.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability1.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setZero(buildingVulnerability1.getTen());
            }
            if ("1".equals(buildingVulnerability2.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability2.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setOne(buildingVulnerability2.getTen());
            }
            if ("2".equals(buildingVulnerability3.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability3.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setTwo(buildingVulnerability3.getTen());
            }
            if ("3".equals(buildingVulnerability4.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability4.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setThree(buildingVulnerability4.getTen());
            }
            if ("4".equals(buildingVulnerability5.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability5.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFour(buildingVulnerability5.getTen());
            }
            if ("5".equals(buildingVulnerability6.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability6.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFive(buildingVulnerability6.getTen());
            }
            if ("6".equals(buildingVulnerability7.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability7.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setSix(buildingVulnerability7.getTen());
            }
            if ("7".equals(buildingVulnerability8.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability8.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setSeven(buildingVulnerability8.getTen());
            }
            if ("8".equals(buildingVulnerability9.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability9.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setEight(buildingVulnerability9.getTen());
            }
            voList5.add(vo);
            listMap.put("10", voList5);
        }
        map = new HashMap<>();
        map.put("code", "200");
        map.put("listMap", listMap);
        return map;
    }

    /**
     * 判断是否有重复的 结构类型-地震烈度-破坏程度
     * 每个 结构类型-地震烈度-破坏程度 只能存在一条
     *
     * @param list
     * @param dzIntensity
     * @param structureType
     * @param destroy
     * @return
     */
    private Map<String, Object> isRepeat(List<String> list, String dzIntensity, String structureType, String destroy) {
        Map<String, Object> map = new HashMap<>();
        if (list.contains(dzIntensity + "-" + structureType + "-" + destroy)) {
            map.put("code", "500");
            switch (structureType) {
                case "0":
                    structureType = "高层结构";
                    break;
                case "1":
                    structureType = "钢结构";
                    break;
                case "2":
                    structureType = "混凝土结构";
                    break;
                case "3":
                    structureType = "砖混结构";
                    break;
                case "4":
                    structureType = "砖木结构";
                    break;
                case "5":
                    structureType = "土结构";
                    break;
                case "6":
                    structureType = "木结构";
                    break;
                case "7":
                    structureType = "石结构";
                    break;
                case "8":
                    structureType = "其他结构";
                    break;
            }
            switch (destroy) {
                case "0":
                    destroy = "基本完好";
                    break;
                case "1":
                    destroy = "轻微破坏";
                    break;
                case "2":
                    destroy = "中等破坏";
                    break;
                case "3":
                    destroy = "严重破坏";
                    break;
                case "4":
                    destroy = "毁坏";
                    break;
            }
            System.out.println("------建筑物易损性list:{}" + list.toString());
            map.put("msg", "建筑物易损性烈度为" + dzIntensity + "的" + structureType + "的" + destroy + "的破坏程度的数据有异常！");
            return map;
        }
        list.add(dzIntensity + "-" + structureType + "-" + destroy);
        return null;
    }

    //@Override
//     @Transactional(rollbackFor = Exception.class)
//     public void calculate2(String modeId, String taskId) throws Exception {
//         basicDataService.deleteSettingSeismicPbeByTaskId(taskId);
//         Long start = System.currentTimeMillis();
//         Casualty model = casualtyRepository.getModelById(modeId);
//         @NotNull(message = "计算死亡人数系数不能为空") BigDecimal deathNumber = model.getDeathNumber();
//         @NotNull(message = "受伤人数系数不能为空") BigDecimal injuries = model.getInjuries();
//         if (PlatformObjectUtils.isEmpty(model)) {
//             throw new RuntimeException("请选择人员伤亡模型");
//         }
//         List<CenterResult> centerList = new ArrayList<>();
// //        List<Vulnerability> allVulnerability = basicDataService.getAllVulnerabilityByTaskId(taskId);
//         Map<String, List<BigDecimal>> structureAndIntensityMap = new HashMap<>();
// //        if (PlatformObjectUtils.isNotEmpty(allVulnerability)) {
// //            //<建筑物类别,<损坏,0.25>>
// //            structureAndIntensityMap = getStructureAndIntensity(allVulnerability);
// //        }
//         //basicDataService.deleteCenterResultByTaskId(taskId);
//         List<SettingSeismicDetails> settingSeismicDetails = settingSeismicService.getSettingSeismicDetailsByTaskId(taskId);
//         if (PlatformObjectUtils.isNotEmpty(settingSeismicDetails)) {
//             //总的死亡人数
//             BigDecimal maxDeathPerson = new BigDecimal(0);
//             BigDecimal minDeathPerson = new BigDecimal(0);
//             //最大最小受伤人数
//             BigDecimal maxInjuredPerson = new BigDecimal(0);
//             BigDecimal minInjuredPerson = new BigDecimal(0);
//             BigDecimal earthLevel = settingSeismicDetails.get(0).getEarthquakeLevel();
//             String id = settingSeismicDetails.get(0).getId();
//             //死亡人数
//             BigDecimal deathTotalNum = new BigDecimal(0);
//             //受伤人数
//             BigDecimal injuredTotalNum = new BigDecimal(0);
//             SettingSeismicDetails detail = null;
//             for (int dd = 0; dd < settingSeismicDetails.size(); dd++) {
//                 detail = settingSeismicDetails.get(dd);
//                 String macroPosition = detail.getMacroPosition();
//                 String province = "";
//                 String city = "";
//                 String country = "";
//                 if (StringUtils.isNotBlank(macroPosition)) {
//                     province = macroPosition.split(",")[0];
//                     city = macroPosition.split(",")[1];
//                     country = macroPosition.split(",")[2];
//                 }
//
//                 if (deathTotalNum.compareTo(maxDeathPerson) > 0) {
//                     maxDeathPerson = deathTotalNum;
//                 }
//                 if (deathTotalNum.compareTo(minDeathPerson) < 0) {
//                     minDeathPerson = deathTotalNum;
//                 }
//                 if (injuredTotalNum.compareTo(maxInjuredPerson) > 0) {
//                     maxInjuredPerson = injuredTotalNum;
//                 }
//                 if (injuredTotalNum.compareTo(minInjuredPerson) < 0) {
//                     minInjuredPerson = injuredTotalNum;
//                 }
//                 deathTotalNum = new BigDecimal(0);
//                 injuredTotalNum = new BigDecimal(0);
//                 List<SettingSeismicInfluenceflied> influenceList = settingSeismicInfluencefliedRepository.findSettingSeismicInfluencefliedById(settingSeismicDetails.get(dd).getId());
//                 if (PlatformObjectUtils.isNotEmpty(influenceList)) {
//                     for (int bb = 0; bb < influenceList.size(); bb++) {
//                         List<Vulnerability> allVulnerability = preAssessResultService.matrixSee(province, city, country, taskId, influenceList.get(bb).getDzIntensity());
//                         if (PlatformObjectUtils.isNotEmpty(allVulnerability)) {
//                             //<建筑物类别,<损坏,0.25>>
//                             structureAndIntensityMap = getStructureAndIntensity(allVulnerability, influenceList.get(bb).getDzIntensity());
//                         }
//                         List<PbeEntity> pbeList = pbeService.getPbeByInfluenceflieId(influenceList.get(bb).getUuid());
//                         if (PlatformObjectUtils.isNotEmpty(pbeList)) {
//                             for (PbeEntity pbeEntity : pbeList) {
//                                 //地震id
//                                 String earthquakeId = influenceList.get(bb).getSourceEarthquakeId();
//                                 //影响场id
//                                 String influenceflieId = influenceList.get(bb).getUuid();
//                                 //格网id
//                                 String pbeId = pbeEntity.getPbeId();
//                                 //获取格网下的面积
//                                 BigDecimal area = new BigDecimal(pbeEntity.getCoveredarea());
//                                 if (area.compareTo(new BigDecimal(0)) == 0) {
//                                     continue;
//                                 }
//                                 BigDecimal hRatio = new BigDecimal(0);
//                                 BigDecimal steelRatio = new BigDecimal(0);
//                                 BigDecimal cRatio = new BigDecimal(0);
//                                 BigDecimal bRatio = new BigDecimal(0);
//                                 BigDecimal bmRatio = new BigDecimal(0);
//                                 BigDecimal sRatio = new BigDecimal(0);
//                                 BigDecimal wRatio = new BigDecimal(0);
//                                 BigDecimal stRatio = new BigDecimal(0);
//                                 BigDecimal oRatio = new BigDecimal(0);
//
//                                 StructuralProportionVo structuralProportion = preAssessResultService.getStructuralProportion(pbeEntity);
//                                 if (PlatformObjectUtils.isNotEmpty(structuralProportion)) {
//                                     if ("城镇".equals(pbeEntity.getTownorcontry())) {
//                                         hRatio = structuralProportion.getDhpTownHighTatio();
//                                         steelRatio = structuralProportion.getDhpTownSteelTatio();
//                                         cRatio = structuralProportion.getDhpTownBetonTatio();
//                                         bRatio = structuralProportion.getDhpTownBrickTatio();
//                                         bmRatio = structuralProportion.getDhpTownMasonryTatio();
//                                         sRatio = structuralProportion.getDhpTownSoilTatio();
//                                         wRatio = structuralProportion.getDhpTownWoodTatio();
//                                         stRatio = structuralProportion.getDhpTownStoneTatio();
//                                         oRatio = structuralProportion.getDhpTownOtherTatio();
//                                     } else if ("农村".equals(pbeEntity.getTownorcontry())) {
//                                         hRatio = structuralProportion.getDhpVillageHighTatio();
//                                         steelRatio = structuralProportion.getDhpVillageSteelTatio();
//                                         cRatio = structuralProportion.getDhpVillageBetonTatio();
//                                         bRatio = structuralProportion.getDhpVillageBrickTatio();
//                                         bmRatio = structuralProportion.getDhpVillageMasonryTatio();
//                                         sRatio = structuralProportion.getDhpVillageSoilTatio();
//                                         wRatio = structuralProportion.getDhpVillageWoodTatio();
//                                         stRatio = structuralProportion.getDhpVillageStoneTatio();
//                                         oRatio = structuralProportion.getDhpVillageOtherTatio();
//                                     }
//                                 } else {
//                                     throw new RuntimeException("获取不到对应的建筑物比例");
//                                 }
//
//                                 //拿到格网下的每类建筑物的占比窃取每类建筑物的面积
//                                 //假设面积比例
//                                 //高层建筑 0.1
//                                 BigDecimal hArea = area.multiply(hRatio);
//                                 //钢结构 0.1
//                                 BigDecimal steelArea = area.multiply(steelRatio);
//                                 //多层钢筋混凝土结构 0.2
//                                 BigDecimal cArea = area.multiply(cRatio);
//                                 ;
//                                 //砖混结构 0.15
//                                 BigDecimal bArea = area.multiply(bRatio);
//                                 ;
//                                 //砖木结构 0.15
//                                 BigDecimal bmArea = area.multiply(bmRatio);
//                                 ;
//                                 //土结构 0.15
//                                 BigDecimal sArea = area.multiply(sRatio);
//                                 ;
//                                 //木结构 0.1
//                                 BigDecimal wArea = area.multiply(wRatio);
//                                 ;
//                                 //石结构 0.1
//                                 BigDecimal stArea = area.multiply(stRatio);
//                                 ;
//                                 //其他结构 0.05
//                                 BigDecimal oArea = area.multiply(oRatio);
//                                 ;
//                                 //拿到建筑物易损性信息求取该格网下每类建筑物的易损面积
//                                 //总的损坏面积=各类建筑类别的损坏面积之和
//                                 BigDecimal totalDdArea = new BigDecimal(0);
//                                 if (structureAndIntensityMap.size() > 0) {
//                                     Iterator<Map.Entry<String, List<BigDecimal>>> iterator = structureAndIntensityMap.entrySet().iterator();
//                                     while (iterator.hasNext()) {
//                                         BigDecimal temp = new BigDecimal(0);
//                                         Map.Entry<String, List<BigDecimal>> next = iterator.next();
//                                         String structureType = next.getKey();
//                                         List<BigDecimal> vulnerability = next.getValue();
//                                         BigDecimal basic = null;
//                                         BigDecimal slight = null;
//                                         BigDecimal mid = null;
//                                         BigDecimal serious = null;
//                                         BigDecimal damage = null;
//                                         if (PlatformObjectUtils.isNotEmpty(vulnerability)) {
//                                             basic = vulnerability.get(0);
//                                             slight = vulnerability.get(1);
//                                             mid = vulnerability.get(2);
//                                             serious = vulnerability.get(3);
//                                             damage = vulnerability.get(4);
//                                             if (FxfzConstants.HIGH_STRUCTURE.equals(structureType)) {
//                                                 temp = hArea;
//                                             } else if (FxfzConstants.STEEL_STRUCTURE.equals(structureType)) {
//                                                 temp = steelArea;
//                                             } else if (FxfzConstants.HNT_STRUCTURE.equals(structureType)) {
//                                                 temp = cArea;
//                                             } else if (FxfzConstants.ZH_STRUCTURE.equals(structureType)) {
//                                                 temp = bArea;
//                                             } else if (FxfzConstants.ZM_STRUCTURE.equals(structureType)) {
//                                                 temp = bmArea;
//                                             } else if (FxfzConstants.SOIL_STRUCTURE.equals(structureType)) {
//                                                 temp = sArea;
//                                             } else if (FxfzConstants.WOOD_STRUCTURE.equals(structureType)) {
//                                                 temp = wArea;
//                                             } else if (FxfzConstants.STONE_STRUCTURE.equals(structureType)) {
//                                                 temp = stArea;
//                                             } else if (FxfzConstants.OTHER_STRUCTURE.equals(structureType)) {
//                                                 temp = oArea;
//                                             }
//                                             //获取不同破损程度下的不同建筑物类别的面积
//                                             //基本完好
//                                             BigDecimal bdArea = basic.compareTo(new BigDecimal(0.00)) == 0 ? basic : basic.multiply(temp);
//                                             //轻微破坏
//                                             BigDecimal sdArea = slight.compareTo(new BigDecimal(0.00)) == 0 ? slight : slight.multiply(temp);
//                                             //中等破坏
//                                             BigDecimal mdArea = mid.compareTo(new BigDecimal(0.00)) == 0 ? mid : mid.multiply(temp);
//                                             //严重破坏
//                                             BigDecimal sedArea = serious.compareTo(new BigDecimal(0.00)) == 0 ? serious : serious.multiply(temp);
//                                             //损坏
//                                             BigDecimal ddArea = damage.compareTo(new BigDecimal(0.00)) == 0 ? damage : damage.multiply(temp);
//                                             totalDdArea = totalDdArea.add(ddArea);
//                                             //保存计算中间结果
//                                             CenterResult centerResult = new CenterResult();
//                                             centerResult.setTaskId(taskId);
//                                             centerResult.setEarthquakeId(earthquakeId);
//                                             centerResult.setInfluenceflieId(influenceflieId);
//                                             centerResult.setPbeId(pbeId);
//                                             centerResult.setStructureType(structureType);
//                                             centerResult.setBasicArea(bdArea);
//                                             centerResult.setBasic(basic);
//                                             centerResult.setSlightArea(sdArea);
//                                             centerResult.setSlight(slight);
//                                             centerResult.setMidArea(mdArea);
//                                             centerResult.setMid(mid);
//                                             centerResult.setSeriousArea(sedArea);
//                                             centerResult.setSerious(serious);
//                                             centerResult.setDamageArea(ddArea);
//                                             centerResult.setDamage(damage);
//                                             centerResult.setArea(area);
//                                             centerResult.setPopulation(new BigDecimal(pbeEntity.getPopulation()));
//                                             centerList.add(centerResult);
//                                             // basicDataService.save(centerResult);
//                                         }
//                                     }
//                                 }
//                                 //计算死亡比
//                                 BigDecimal deathPercent = totalDdArea.divide(area, 2, BigDecimal.ROUND_HALF_UP);
//                                 //计算死亡人数
//                                 BigDecimal deathPersonCount = deathNumber.multiply(new BigDecimal(pbeEntity.getPopulation())).multiply(deathPercent);
//                                 deathTotalNum = deathTotalNum.add(deathPersonCount);
//                                 BigDecimal injuryPerson = deathPersonCount.multiply(injuries);
//                                 injuredTotalNum = injuredTotalNum.add(injuryPerson);
//                                 TaskPbe pbe = new TaskPbe();
//                                 pbe.setUuid(UUIDGenerator.getUUID());
//                                 pbe.setEarthquakeId(earthquakeId);
//                                 pbe.setInfluencefliedId(influenceflieId);
//                                 pbe.setPbeId(pbeId);
//                                 pbe.setTaskId(taskId);
//                                 pbe.setDeathPercent(deathPercent);
//                                 pbe.setDeathPerson(deathPersonCount.intValue());
//                                 pbe.setInjuryPerson(injuryPerson.intValue());
//                                 basicDataService.insertTaskPbe(pbe);
//                             }
//                         }
//                     }
//                 }
//                 if (dd == 0) {
//                     maxDeathPerson = deathTotalNum;
//                     minDeathPerson = deathTotalNum;
//                     maxInjuredPerson = injuredTotalNum;
//                     minInjuredPerson = injuredTotalNum;
//                 }
// //                ResultDetailsEntity resultDetailsEntity = new ResultDetailsEntity();
// //                resultDetailsEntity.setTaskId(taskId);
// //                resultDetailsEntity.setLongitude(settingSeismicDetails.get(dd).getLongitude().toString());
// //                resultDetailsEntity.setLatitude(settingSeismicDetails.get(dd).getLatitude().toString());
// //                resultDetailsEntity.setMagnitude(settingSeismicDetails.get(dd).getEarthquakeLevel());
// //                resultDetailsEntity.setDeathToll(String.valueOf(deathTotalNum.intValue()));
// //                resultDetailsEntity.setInjuredNum(String.valueOf(injuredTotalNum.intValue()));
// //                resultDetailsEntity.setDataSource("2");
// //                resultDetailsEntity.setAngle(String.valueOf(settingSeismicDetails.get(dd).getAngle()));
// //                resultTotalRepository.updateResultDetailsEntity(resultDetailsEntity);
//                 createResultDetailsEntity(taskId, settingSeismicDetails.get(dd), deathTotalNum, injuredTotalNum);
//                 if (!settingSeismicDetails.get(dd).getEarthquakeLevel().equals(earthLevel)) {
// //                    ResultMainEntity resultMainEntity = new ResultMainEntity();
// //                    resultMainEntity.setTaskId(taskId);
// //                    resultMainEntity.setLongitude(settingSeismicDetails.get(dd-1).getLongitude().toString());
// //                    resultMainEntity.setLatitude(settingSeismicDetails.get(dd-1).getLatitude().toString());
// //                    resultMainEntity.setMagnitude(settingSeismicDetails.get(dd-1).getEarthquakeLevel());
// //                    resultMainEntity.setMagnitude(settingSeismicDetails.get(dd-1).getEarthquakeLevel());
// //                    resultMainEntity.setDeathTollBefore(minDeathPerson.compareTo(maxDeathPerson)==0?minDeathPerson.intValue()+"":(minDeathPerson.intValue()+"-"+maxDeathPerson.intValue()));
// //                    resultMainEntity.setDeathTollAfter(minDeathPerson.compareTo(maxDeathPerson)==0?minDeathPerson.intValue()+"":(minDeathPerson.intValue()+"-"+maxDeathPerson.intValue()));
// //                    resultMainEntity.setInjuredNumBefore(minInjuredPerson.compareTo(maxInjuredPerson)==0?minInjuredPerson.intValue()+"":(minInjuredPerson.intValue()+"-"+maxInjuredPerson.intValue()));
// //                    resultMainEntity.setInjuredNumAfter(minInjuredPerson.compareTo(maxInjuredPerson)==0?minInjuredPerson.intValue()+"":(minInjuredPerson.intValue()+"-"+maxInjuredPerson.intValue()));
// //                    resultMainEntity.setDataSource("2");
// //                    resultTotalRepository.updateResultTotal(resultMainEntity);
//                     createResultMainEntity(taskId, settingSeismicDetails.get(dd - 1), minDeathPerson, maxDeathPerson, minInjuredPerson, maxInjuredPerson);
//                     maxDeathPerson = deathTotalNum;
//                     minDeathPerson = deathTotalNum;
//                     maxInjuredPerson = injuredTotalNum;
//                     minInjuredPerson = injuredTotalNum;
//                     earthLevel = settingSeismicDetails.get(dd).getEarthquakeLevel();
//                 }
//             }
//             if (deathTotalNum.compareTo(maxDeathPerson) > 0) {
//                 maxDeathPerson = deathTotalNum;
//             }
//             if (deathTotalNum.compareTo(minDeathPerson) < 0) {
//                 minDeathPerson = deathTotalNum;
//             }
//             if (injuredTotalNum.compareTo(maxInjuredPerson) > 0) {
//                 maxInjuredPerson = injuredTotalNum;
//             }
//             if (injuredTotalNum.compareTo(minInjuredPerson) < 0) {
//                 minInjuredPerson = injuredTotalNum;
//             }
// //            ResultMainEntity resultMainEntity = new ResultMainEntity();
// //            resultMainEntity.setTaskId(taskId);
// //            resultMainEntity.setLongitude(detail.getLongitude().toString());
// //            resultMainEntity.setLatitude(detail.getLatitude().toString());
// //            resultMainEntity.setMagnitude(detail.getEarthquakeLevel());
// //            resultMainEntity.setDataSource("2");
// //            resultMainEntity.setDeathTollBefore(minDeathPerson.compareTo(maxDeathPerson)==0?minDeathPerson.intValue()+"":(minDeathPerson.intValue()+"-"+maxDeathPerson.intValue()));
// //            resultMainEntity.setDeathTollAfter(minDeathPerson.compareTo(maxDeathPerson)==0?minDeathPerson.intValue()+"":(minDeathPerson.intValue()+"-"+maxDeathPerson.intValue()));
// //            resultMainEntity.setInjuredNumBefore(minInjuredPerson.compareTo(maxInjuredPerson)==0?minInjuredPerson.intValue()+"":(minInjuredPerson.intValue()+"-"+maxInjuredPerson.intValue()));
// //            resultMainEntity.setInjuredNumAfter(minInjuredPerson.compareTo(maxInjuredPerson)==0?minInjuredPerson.intValue()+"":(minInjuredPerson.intValue()+"-"+maxInjuredPerson.intValue()));
// //            resultTotalRepository.updateResultTotal(resultMainEntity);
//             createResultMainEntity(taskId, detail, minDeathPerson, maxDeathPerson, minInjuredPerson, maxInjuredPerson);
//         }
//         //if(PlatformObjectUtils.isEmpty(resultList)){
//         if (PlatformObjectUtils.isNotEmpty(centerList)) {
//             for (CenterResult result : centerList) {
//                 basicDataService.save(result);
//             }
//         }
//         //}
//         Long end = System.currentTimeMillis();
//         System.out.println("总消耗时间是:" + (end - start) / 1000);
//     }

    private void createResultDetailsEntity(String taskId, SettingSeismicDetails settingSeismicDetails, BigDecimal deathTotalNum, BigDecimal injuredTotalNum) {
        ResultDetailsEntity resultDetailsEntity = new ResultDetailsEntity();
        resultDetailsEntity.setTaskId(taskId);
        resultDetailsEntity.setLongitude(settingSeismicDetails.getLongitude().toString());
        resultDetailsEntity.setLatitude(settingSeismicDetails.getLatitude().toString());
        resultDetailsEntity.setMagnitude(settingSeismicDetails.getEarthquakeLevel());
        resultDetailsEntity.setDeathToll(String.valueOf(deathTotalNum.intValue()));
        resultDetailsEntity.setInjuredNum(String.valueOf(injuredTotalNum.intValue()));
        resultDetailsEntity.setDataSource("2");
        resultDetailsEntity.setAngle(String.valueOf(settingSeismicDetails.getAngle()));
        resultTotalRepository.updateResultDetailsEntity(resultDetailsEntity);
    }

    private void createResultMainEntity(String taskId, SettingSeismicDetails settingSeismicDetails, BigDecimal minDeathPerson, BigDecimal maxDeathPerson, BigDecimal minInjuredPerson, BigDecimal maxInjuredPerson) {
        ResultMainEntity resultMainEntity = new ResultMainEntity();
        resultMainEntity.setTaskId(taskId);
        resultMainEntity.setLongitude(settingSeismicDetails.getLongitude().toString());
        resultMainEntity.setLatitude(settingSeismicDetails.getLatitude().toString());
        resultMainEntity.setMagnitude(settingSeismicDetails.getEarthquakeLevel());
        resultMainEntity.setMagnitude(settingSeismicDetails.getEarthquakeLevel());
        resultMainEntity.setDeathTollBefore(minDeathPerson.compareTo(maxDeathPerson) == 0 ? minDeathPerson.intValue() + "" : (minDeathPerson.intValue() + "-" + maxDeathPerson.intValue()));
        resultMainEntity.setDeathTollAfter(minDeathPerson.compareTo(maxDeathPerson) == 0 ? minDeathPerson.intValue() + "" : (minDeathPerson.intValue() + "-" + maxDeathPerson.intValue()));
        resultMainEntity.setInjuredNumBefore(minInjuredPerson.compareTo(maxInjuredPerson) == 0 ? minInjuredPerson.intValue() + "" : (minInjuredPerson.intValue() + "-" + maxInjuredPerson.intValue()));
        resultMainEntity.setInjuredNumAfter(minInjuredPerson.compareTo(maxInjuredPerson) == 0 ? minInjuredPerson.intValue() + "" : (minInjuredPerson.intValue() + "-" + maxInjuredPerson.intValue()));
        resultMainEntity.setDataSource("2");
        resultTotalRepository.updateResultTotal(resultMainEntity);
    }


    //    private Map<String, Vulnerability> getStructureAndIntensity(List<Vulnerability> allVulnerability) {
//        Map<String, Vulnerability> map = new HashMap<>();
//        for (Vulnerability taskVulnerability : allVulnerability) {
//            String structureType = taskVulnerability.getStructureType();
//            map.put(structureType,taskVulnerability);
//        }
//        return map;
//    }
    private Map<String, List<BigDecimal>> getStructureAndIntensity(List<Vulnerability> allVulnerability, String dzIntensity) {
        //Map<String, Vulnerability> map = new HashMap<>();
        Map<String, List<BigDecimal>> map = new HashMap<>();
        List<BigDecimal> dataList = new ArrayList<>();
        for (Vulnerability taskVulnerability : allVulnerability) {
            String structureType = taskVulnerability.getStructureType();
            if (!map.containsKey(structureType)) {
                dataList = new ArrayList<>();
            }
            if ("6".equals(dzIntensity)) {
                dataList.add(taskVulnerability.getSix());
            } else if ("7".equals(dzIntensity)) {
                dataList.add(taskVulnerability.getSeven());
            } else if ("8".equals(dzIntensity)) {
                dataList.add(taskVulnerability.getEight());
            } else if ("9".equals(dzIntensity)) {
                dataList.add(taskVulnerability.getNine());
            } else if ("10".equals(dzIntensity)) {
                dataList.add(taskVulnerability.getTen());
            }
            map.put(structureType, dataList);
        }
        return map;
    }

    private List<Map<String, BigDecimal>> buildVulnerabilityMap(List<BuildingVulnerability> vulnerabilities, String dzIntensity) {
        List<Map<String, BigDecimal>> list = new ArrayList<>();
        for (BuildingVulnerability buildingVulnerability : vulnerabilities) {
            Map<String, BigDecimal> map = new HashMap<>();
            if ("VI".equals(dzIntensity)) {
                map.put(buildingVulnerability.getDestroy(), buildingVulnerability.getSix());
            } else if ("VII".equals(dzIntensity)) {
                map.put(buildingVulnerability.getDestroy(), buildingVulnerability.getSeven());
            } else if ("VIII".equals(dzIntensity)) {
                map.put(buildingVulnerability.getDestroy(), buildingVulnerability.getEight());
            } else if ("IX".equals(dzIntensity)) {
                map.put(buildingVulnerability.getDestroy(), buildingVulnerability.getNine());
            } else if ("X".equals(dzIntensity)) {
                map.put(buildingVulnerability.getDestroy(), buildingVulnerability.getTen());
            }
            list.add(map);
        }
        return list;
    }

    @Override
    public List<DataPbeInjuries> getPbeByTaskIdAndIntensity(String taskId, String dzIntensity) {
        List<DataPbeInjuries> pbeList = casualtyRepository.getPbeInjuries(taskId, dzIntensity);
        return pbeList;
    }

    @Override
    public List<DataPbeInjuries> getTaskPbe(String taskId) {
        return casualtyRepository.getTaskPbe(taskId);
    }

    @Override
    public List<DataPbeInjuriesVo> getTaskPbeVo(String taskId) {
        return casualtyRepository.getTaskPbeVo(taskId);
    }

    @Override
    public Integer getTaskPbeCount(String taskId) {
        return casualtyRepository.getTaskPbeCount(taskId);
    }

    @Override
    public DataPbeIntStrArea findByTaskIdLimit(String taskId) {
        return casualtyRepository.findByTaskIdLimit(taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDataPbeIntStrAreaByTaskId(String taskId) {
        casualtyRepository.deleteDataPbeIntStrAreaByTaskId(taskId);
    }

    //ss
    @Override
    public Casualty getModel1ById(String id) {
        Casualty casualty = casualtyRepository.getModelById(id);
        return casualty;
    }

    @Override
    public DataPbeInjuries findByTaskIdLimit2(String taskId) {
        return casualtyRepository.findByTaskIdLimit2(taskId);
    }
    private void buildData1(List<DataPbeInjuries> dataList,long postName) throws Exception{
        String filePath = localDir+File.separator+"各个烈度人员伤亡情况" +postName+ ".shp";
        File file = new File(filePath);
        ShapefileDataStoreFactory sf = new ShapefileDataStoreFactory();
        ShapefileDataStore ds = (ShapefileDataStore) sf.createDataStore(file.toURI().toURL());
        ds.setCharset(Charset.forName("GBK"));
        SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
        tb.setCRS(CRS.decode("EPSG:4490"));
        tb.setName("shapefile");
        tb.add("烈度", String.class);
        tb.add("面积", BigDecimal.class);
        tb.add("人口", BigDecimal.class);
        tb.add("死亡人数", BigDecimal.class);
        tb.add("受伤人数", BigDecimal.class);
        tb.add("死亡系数", BigDecimal.class);
        tb.add("受伤系数", BigDecimal.class);
        tb.add("the_geom", MultiPolygon.class);
        SimpleFeatureType simpleFeatureType = tb.buildFeatureType();
        ds.createSchema(simpleFeatureType);
        FeatureWriter featureWriter = ds.getFeatureWriter(ds.getTypeNames()[0], null);
        for (DataPbeInjuries seiCapDistribution : dataList) {
            SimpleFeature feature = (SimpleFeature) featureWriter.next();
            feature.setAttribute(1, seiCapDistribution.getDzIntentity());
            feature.setAttribute(2, seiCapDistribution.getCoveredarea());
            feature.setAttribute(3, seiCapDistribution.getPopulation());
            feature.setAttribute(4, seiCapDistribution.getDeathNum());
            feature.setAttribute(5, seiCapDistribution.getInjuriesNum());
            feature.setAttribute(6, seiCapDistribution.getDeath());
            feature.setAttribute(7, seiCapDistribution.getInjuries());
            String geom =  seiCapDistribution.getGeomText();
            feature.setAttribute("the_geom", geom);
        }
        featureWriter.write();
        featureWriter.close();
        ds.dispose();
    }
    @Override
    public void exportPbeInjuries(String taskId, HttpServletResponse resp) throws Exception{
        List<DataPbeInjuries> dataList = casualtyRepository.getTaskPbe(taskId);
        if(PlatformObjectUtils.isEmpty(dataList) || dataList.size()==0){
            throw new RuntimeException("导出失败，未查询到各个烈度下的人员伤亡数据");
        }
        long postName = System.currentTimeMillis();
        buildData1(dataList,postName);
        String zipPath = localDir +File.separator+ "各个烈度人员伤亡情况"+System.currentTimeMillis()+ ".zip";
        InputStream input = null;
        ZipOutputStream zipOut = null;

        File zipFile = new File(zipPath);
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            // zip的名称为
            zipOut.setComment("各个烈度人员伤亡情况");
            String[] shpFiles = new String[]{
                    localDir + File.separator  + "各个烈度人员伤亡情况"+postName+".dbf",
                    localDir + File.separator  + "各个烈度人员伤亡情况"+postName+".prj",
                    localDir + File.separator  + "各个烈度人员伤亡情况"+postName+".shp",
                    localDir + File.separator  + "各个烈度人员伤亡情况"+postName+".shx",
                    localDir + File.separator  + "各个烈度人员伤亡情况"+postName+".fix"
            };
            for (int i = 0; i < shpFiles.length; i++) {
                File file1 = new File(shpFiles[i]);
                input = new FileInputStream(file1);
                zipOut.putNextEntry(new ZipEntry(file1.getName()));
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    zipOut.write(temp);
                }
            }
            for (String shpFile : shpFiles) {
                //删除生成的临时文件
                File file1 = new File(shpFile);
                file1.deleteOnExit();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                input.close();
            }
            if (zipOut != null) {
                zipOut.close();
            }
        }
        export(zipFile,resp);
    }

    @Override
    public void exportIntensityAndStructureOfArea(String taskId,HttpServletResponse resp) throws Exception{
        List<DataPbeIntStrArea> dataList = casualtyRepository.getDataPbeIntStrAreaByTaskId(taskId, "4");
        if(PlatformObjectUtils.isEmpty(dataList) || dataList.size()==0){
            throw new RuntimeException("导出失败，未查询到各个烈度下的建筑物破坏数据");
        }
        long postName = System.currentTimeMillis();
        buildData(dataList,postName);
        String zipPath = localDir +File.separator+ "各个烈度不同建筑物破坏情况"+System.currentTimeMillis()+ ".zip";
        InputStream input = null;
        ZipOutputStream zipOut = null;

        File zipFile = new File(zipPath);
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            // zip的名称为
            zipOut.setComment("各个烈度不同建筑物破坏情况");
            String[] shpFiles = new String[]{
                    localDir + File.separator  + "各个烈度不同建筑物破坏情况"+postName+".dbf",
                    localDir + File.separator  + "各个烈度不同建筑物破坏情况"+postName+".prj",
                    localDir + File.separator  + "各个烈度不同建筑物破坏情况"+postName+".shp",
                    localDir + File.separator  + "各个烈度不同建筑物破坏情况"+postName+".shx",
                    localDir + File.separator  + "各个烈度不同建筑物破坏情况"+postName+".fix"
            };
            for (int i = 0; i < shpFiles.length; i++) {
                File file1 = new File(shpFiles[i]);
                input = new FileInputStream(file1);
                zipOut.putNextEntry(new ZipEntry(file1.getName()));
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    zipOut.write(temp);
                }
            }
            for (String shpFile : shpFiles) {
                //删除生成的临时文件
                File file1 = new File(shpFile);
                file1.deleteOnExit();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                input.close();
            }
            if (zipOut != null) {
                zipOut.close();
            }
        }
        export(zipFile,resp);
    }

    private void export(File zipFile, HttpServletResponse response) throws IOException {
        InputStream fis = new BufferedInputStream(new FileInputStream(zipFile));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
        response.setContentType("application/x-msdownload");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(zipFile.getName(), "UTF-8"));
        response.setHeader("Access-Control-Allow-Origin","*");
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        os.write(buffer);// 输出文件
        os.flush();
        os.close();
    }

    //生成shp文件
    private void buildData(List<DataPbeIntStrArea>  dataList,long postName) throws Exception {
        String filePath = localDir+File.separator+"各个烈度不同建筑物破坏情况" +postName+ ".shp";
        File file = new File(filePath);
        ShapefileDataStoreFactory sf = new ShapefileDataStoreFactory();
        ShapefileDataStore ds = (ShapefileDataStore) sf.createDataStore(file.toURI().toURL());
        ds.setCharset(Charset.forName("GBK"));
        SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
        tb.setCRS(CRS.decode("EPSG:4490"));
        tb.setName("shapefile");
        tb.add("烈度", String.class);
        tb.add("建筑面积", BigDecimal.class);
        tb.add("人口", BigDecimal.class);
        tb.add("高层面积", BigDecimal.class);
        tb.add("钢结构面积", BigDecimal.class);
        tb.add("多层面积", BigDecimal.class);
        tb.add("砖混面积", BigDecimal.class);
        tb.add("砖木面积", BigDecimal.class);
        tb.add("土面积", BigDecimal.class);
        tb.add("木面积", BigDecimal.class);
        tb.add("石面积", BigDecimal.class);
        tb.add("其他面积", BigDecimal.class);
        tb.add("the_geom", MultiPolygon.class);
        SimpleFeatureType simpleFeatureType = tb.buildFeatureType();
        ds.createSchema(simpleFeatureType);
        FeatureWriter featureWriter = ds.getFeatureWriter(ds.getTypeNames()[0], null);
        for (DataPbeIntStrArea seiCapDistribution : dataList) {
            SimpleFeature feature = (SimpleFeature) featureWriter.next();
            feature.setAttribute(1, seiCapDistribution.getDzIntensity());
            feature.setAttribute(2, seiCapDistribution.getCoveredArea());
            feature.setAttribute(3, seiCapDistribution.getPopulation());
            feature.setAttribute(4, seiCapDistribution.getHArea());
            feature.setAttribute(5, seiCapDistribution.getSteelArea());
            feature.setAttribute(6, seiCapDistribution.getCArea());
            feature.setAttribute(7, seiCapDistribution.getBArea());
            feature.setAttribute(8, seiCapDistribution.getBmArea());
            feature.setAttribute(9, seiCapDistribution.getSArea());
            feature.setAttribute(10, seiCapDistribution.getWArea());
            feature.setAttribute(11, seiCapDistribution.getStArea());
            feature.setAttribute(12, seiCapDistribution.getOArea());
            String geom =  seiCapDistribution.getGeomText();
            feature.setAttribute("the_geom", geom);
        }
        featureWriter.write();
        featureWriter.close();
        ds.dispose();
    }
}